JavaScript通过clck更改当前元素的颜色 [英] JavaScript change the color of current element by clck
问题描述
我的问题是,我无法重置上一个元素的背景色.
例如,如果单击旧div"和新div",则我有两种背景颜色(黄色,浅蓝色),然后两个div的背景颜色变为绿色.但只应将一个div设置为绿色.
因此,每次单击都只能更改当前元素的背景颜色.
JavaScript
var divTag = document.getElementsByTagName("div");for(var i = 0; i< divTag.length; i ++){如果(divTag [i] .tagName =="DIV" || divTag [i] .tagName =="div"){如果(divTag [i] .addEventListener){divTag [i] .addEventListener('click',callback,false);}否则,如果(divTag [i] .attachEvent){divTag [i] .attachEvent('on'+'click',callback);}}}函数回调函数(e){e = e ||window.event;var target = e.target ||e.srcElement;target.style.backgroundColor =绿色";e.stopPropagation();}
HTML
< div id ="old">< input style ="margin:10px;"type ="textbox"/>< div id ="new"></div></div>
CSS
#old {宽度:200像素;高度:200px;背景颜色:黄色;}#新的{宽度:20px;高度:20px;背景颜色:浅蓝色;}
你能帮我吗?预先感谢
如果您担心性能,则可以保存以前的内容并将其背景颜色重置为正常颜色.
var prevDiv = null;函数回调函数(e){e = e ||window.event;var target = e.target ||e.srcElement;if(prevDiv){prevDiv.style.backgroundColor ='';}target.style.backgroundColor ='绿色';prevDiv =目标;e.stopPropagation();}
i have a question about changing the color of only Current element. So i want to change the background color of the current element by every click.
My problem is, i can not reset the background color of previous element.
For an example i have here two background color(yellow, lightblue), if i click on "old div" and "new div", than the background color of two divs changes to green. But only one div should be set to green.
So by every click must change only the background color of current element.
JavaScript
var divTag = document.getElementsByTagName("div");
for (var i = 0; i < divTag.length; i++) {
if (divTag[i].tagName == "DIV" || divTag[i].tagName == "div") {
if (divTag[i].addEventListener) {
divTag[i].addEventListener('click', callback,false);
}
else if (divTag[i].attachEvent) {
divTag[i].attachEvent('on' + 'click',callback);
}
}
}
function callback(e) {
e = e || window.event;
var target = e.target || e.srcElement;
target.style.backgroundColor = "green";
e.stopPropagation();
}
HTML
<div id="old">
<input style="margin: 10px;" type="textbox" />
<div id="new"></div>
</div>
CSS
#old {
width:200px;
height:200px;
background-color:yellow;
}
#new{
width:20px;
height:20px;
background-color:lightblue;
}
Can you help me? Thanks in advance
If you worried about performance, you can just save previous and reset it's background color to normal.
var prevDiv = null;
function callback(e) {
e = e || window.event;
var target = e.target || e.srcElement;
if(prevDiv) {
prevDiv.style.backgroundColor = '';
}
target.style.backgroundColor = 'green';
prevDiv = target;
e.stopPropagation();
}
这篇关于JavaScript通过clck更改当前元素的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!