我想知道是否可以将 onmouseover
+ onmouseout
添加到 Javascript 中的 if/else 语句中,例如:
function pan() {
var ID = document.getElementById("grad");
var change = ID.style.backgroundSize = "1200px 500px";
var revert = ID.style.backgroundSize = "1080px 300px";
if (){
change.addEventListener("onmouseover");
}else {
revert.addEventListener("onmouseout");
}
}
我到处都看过,看不出肯定的是或否,除非它是在 jQuery 中,而且我什至还没有看过 jQuery,所以请不要在 jQuery 中给出答案。
如果可能的话,你是怎么做到的?
否则,还有什么选择?
最佳答案
这是可能的,但是你的代码不正确,这里是更正后的代码:
function pan() {
var ID = document.getElementById("grad");
var change = ID.style.backgroundColor = "red";
var revert = ID.style.backgroundColor = "black";
if( true){
ID.addEventListener("mouseover", function(){alert("EVENT OVER")});
}else {
ID.addEventListener("mouseout", function(){alert("EVENT OUt")});
}
}
你可以在元素上绑定(bind)事件。
这是 addEventListener
函数的一些文档 https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
但我假设你会想做这样的事情(我使用 backgroundColor,所以这个例子可以看得更清楚):
var ID = document.getElementById("grad");
function change (event){
event.target.style.backgroundColor = "red";
}
function revert (event){
event.target.style.backgroundColor = "white";
}
ID.addEventListener("mouseover", change);
ID.addEventListener("mouseout", revert);
<div id="grad" style="border:1px solid black">sdfgsdfg</div>
关于javascript - 将事件监听器添加到 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39263189/