JS中判断element.style.bottom为空不生效,如何检测未设置的样式属性?
解决方法
你遇到的两个if同时触发的核心问题,是用了两个独立的if语句而非if-else分支结构。如果操作A中修改了element.style.bottom的值,执行完操作A后,第二个if的条件会变成真,导致操作B也被执行。
正确的切换逻辑
把代码改成二选一的分支结构,就能保证只触发其中一个操作:
const element = document.querySelector('.my-thing'); if (element.style.bottom === "") { // 执行操作A:比如设置bottom值 element.style.bottom = "120px"; } else { // 执行操作B:比如清空bottom值 element.style.bottom = ""; }
关于样式属性的检测
- 检测行内样式的
bottom是否设置:element.style.bottom === ""是完全正确的方式,控制台打印的空字符串就是行内未设置该属性的标志。 - 如果需要判断元素最终渲染的bottom样式(比如通过CSS类、继承等方式设置的),则需要使用
getComputedStyle:
注意:const computedStyle = window.getComputedStyle(element); // 默认未设置时,计算后的bottom值为"auto" if (computedStyle.bottom === "auto") { // 执行操作A } else { // 执行操作B }getComputedStyle仅用于获取最终渲染样式,无法直接修改元素样式,修改仍需通过element.style完成。
内容的提问来源于stack exchange,提问作者rovac
相关产品推荐
相关产品推荐

