我有这个javascript代码:
function changeIn(ele,clr){
var elem = document.getElementById(ele);
elem.style.transition = "background 1.0s linear 0s";
elem.style.background=clr;
}
function changeOut(ele){
var elem=document.getElementById(ele);
elem.style.transition = "background 1.0s linear 0s";
elem.style.background="#9DCEFF";
}
然后我在HTML上调用该函数,
<div id="boxOne" onmouseover="changeIn(this,'#F0F')" onmouseout="changeOut(this)">Some content</div>
但是不要工作。如何使用 this 作为参数将该函数应用于boxOne?感谢。
答案 0 :(得分:3)
this
将传递DOM对象本身,而不是其ID。您不需要getElementById()
请求,因为ele
参数已经引用了DOM元素。只需更新您的两个功能,如下所示:
function changeIn( ele, clr )
{
ele.style.transition = "background 1.0s linear 0s";
ele.style.background=clr;
}
function changeOut( ele )
{
ele.style.transition = "background 1.0s linear 0s";
ele.style.background="#9DCEFF";
}
答案 1 :(得分:2)
您不需要在方法内再次找到该元素。只需使用您的参数
function changeIn(ele,clr){
ele.style.transition = "background 1.0s linear 0s";
ele.style.background=clr;
}
导致问题的一行是
var elem = document.getElementById(ele);
此处ele
是一个DOM元素,而不是元素的ID。因此,上述表达式的结果变量即elem
变为undefined
。所以你可以直接在你的函数中使用DOM元素。
答案 2 :(得分:1)
试试这个:
function changeIn(ele,clr){
ele.style.transition = "background 1.0s linear 0s";
ele.style.background=clr;
}
function changeOut(ele){
ele.style.transition = "background 1.0s linear 0s";
ele.style.background="#9DCEFF";
}
在onmouseover="changeIn(this,'#F0F')"
函数的div [{1}} this
== ele
中。
所以你不需要找到元素
changeIn(ele,clr)
因为var elem = document.getElementById(ele);
已经是DOM元素。希望这能帮到你!
答案 3 :(得分:1)
this
对象已经是您寻找的DOM元素。演示:
<div id="boxOne" onmouseover="changeIn(this,'#F0F')" onmouseout="changeOut(this)">Some content</div>
window.changeIn = function(elem,clr){
elem.style.transition = "background 1.0s linear 0s";
elem.style.backgroundColor=clr;
};
window.changeOut = function(elem){
elem.style.transition = "background 1.0s linear 0s";
elem.style.backgroundColor="#9DCEFF";
};
答案 4 :(得分:1)
您可以使用event.target
。
Jsfiddle:http://jsfiddle.net/74y7exp3/
function changeIn(clr){
var elem = event.target;
elem.style.transition = "background 1.0s linear 0s";
elem.style.background=clr;
}
function changeOut(ele){
var elem=event.target;
elem.style.transition = "background 1.0s linear 0s";
elem.style.background="#9DCEFF";
}
答案 5 :(得分:1)
你也可以试试这个: -
function changeIn(ele,clr){
var elem = document.getElementById(ele.id);
elem.style.transition = "background 1.0s linear 0s";
elem.style.background=clr;
}
function changeOut(ele){
var elem=document.getElementById(ele.id);
elem.style.transition = "background 1.0s linear 0s";
elem.style.background="#9DCEFF";
}
<div id="boxOne" onmouseover="changeIn(this,'#F0F')" onmouseout="changeOut(this)">Some content</div>