https://codepen.io/SmileySteven/pen/pdBYdv?editors=1111
function test(){
var span = document.querySelectorAll('span');
for(var i = 0 ; i <= span.length ;i++){
span.addEventListener('click', function(){
this.style.backgroundColor === '#ffffff'? this.style.backgroundColor = 'yellow'
: this.style.backgroundColor="#000000";
})
}
}
test();
大家好,我正在尝试改变我的跨度的背景颜色点击,但它似乎没有工作-关心引导我做错了什么?我已将所有跨度设置为#ffffff
的背景色
发布于 2017-12-06 06:24:29
span.addEventListener('click', function(){
您正在将事件设置为跨度的整个集合。您应该设置为单个元素
span[i].addEventListener('click', function(){
发布于 2017-12-06 06:41:24
function test(){
var span = document.querySelectorAll('span');
span.forEach((item)=>{
item.addEventListener('click',()=>{
let styles = getComputedStyle(item);
styles.backgroundColor == 'rgb(255, 255, 255)' ? item.style.backgroundColor = 'yellow' : item.style.backgroundColor = 'black';
});
});
}
test();
.def.def2{
background-color:orange
}
div#ya{
background-color:purple
}
span{
background-color:#ffffff
}
<input type="text" id="i1"> </input>
<input type="text" id="i2"> </input>
<input type="number" id="i3"> </input>
<button id="btn"> sad </button>
<div> Div1 </div>
<div class="def def2"> div2 </div>
<div id="ya" class="def def2 def3 omg"> div2 </div>
<p> sad </p>
<span > test </span><span> test </span><span> test </span>
我推荐在querySelectorAll()
中使用forEach
。
而且,如果你想得到background-color
的值,你最好使用getComputedStyle()
。
但是,getComputedStyle().backgroundColor
总是返回rgb()
,所以你必须使用rgb()
。
发布于 2017-12-06 07:41:58
1 - JavaScript always garbing 白色backgrounds From HTML as 空用于打印。
所以如果你想要匹配的背景是白色的
然后用替换:
this.style.backgroundColor === '#ffffff' ? ..... etc ;
有了这个:
this.style.backgroundColor === "" ? this.style.backgroundColor = 'yellow'
: this.style.backgroundColor="#000000";
否则,如果您尝试匹配的背景是白色而不是
然后,您可以使用条件normal element === " color code here "
2 -最后,正如其他人提到的那样,在您的span回调前面添加循环,如下所示:
span[i].addEventListener('click', function(){ ... etc
https://stackoverflow.com/questions/47668027
复制相似问题