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"
中的元素上设置的样式,这不包括附加的样式来自 style
或 link
标签。
否则你会使用 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>