javascript button.style.backgroundColor 返回 ""直到被点击

标签 javascript css

<分区>

function chgBkColor(v) {
  v.style.backgroundColor === "rgb(255, 255, 255)" ?
    v.style.backgroundColor = "#50AAD7" :
    v.style.backgroundColor = "#fff"
};
.dowBtn {
  background-color: #fff;
  border-radius: 0.7em;
  border: 1px solid #ddd;
}
<button onclick='chgBkColor(this);' id="su" class="dowBtn">Su</button>

当我单击该按钮时,第一次单击无效并且 v.style 为空白。我已经使用 documentGetElementById 尝试了各种方法,并且都以相同的方式发生。

每次点击后都可以很好地切换背景颜色。

最佳答案

它不起作用,因为你没有初始化颜色,所以它不等于任何东西,所以它应用白色:

<button onclick='chgBkColor(this);' id="su" class="dowBtn" style="background-color: #fff">Su</button>

当使用 .style.xxx 时,您正在访问直接在属性 style="xxx" 中的元素上设置的样式,这不包括附加的样式来自 stylelink 标签。

否则你会使用 getComputedStyle()

The Window.getComputedStyle() method returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain. Individual CSS property values are accessed through APIs provided by the object, or by indexing with CSS property names.

这考虑了在 css 类中设置的值,而不仅仅是在元素上设置的值,基本上您正在访问它的当前视觉样式。

function chgBkColor(v) {
    getComputedStyle(v).backgroundColor === "rgb(255, 255, 255)" ?
            v.style.backgroundColor = "#50AAD7" :
                    v.style.backgroundColor = "#fff"
};
.dowBtn {
    background-color: #fff;
    border-radius: 0.7em;
    border: 1px solid #ddd;
}
<button onclick='chgBkColor(this);' id="su" class="dowBtn">Btn 1</button>

关于javascript button.style.backgroundColor 返回 ""直到被点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55108853/

相关文章:

jquery - float Div、水平滚动和 Animate.Scrollleft 合而为一

css - 包含元素边缘的工具提示截断

javascript - 连接表格单元格值并通过 javascript 重新格式化

javascript - 未捕获( promise )类型错误 : Failed to fetch - Service worker with workbox

css - 应用于文本的透明线性渐变 - Safari 中的错误

javascript - 使用 wordpress 悬停时显示/隐藏图像缩略图标签

html - 使最后一个元素占用剩余的宽度(并支持 IE9)

php - 将值数组作为发布数据传递给 document.forms[].method?

javascript - 使用js将一个div的高度设置为与另一个div相同的高度

javascript - Bower 组件出现 404 错误