1

我有一个元素:

<b onclick="alert('');" onmouseover="this.style.color='red'; setTimeout('........', 1000);" onmouseout="this.style.color='';">123</b>

我需要当元素被鼠标悬停并且 1 秒后鼠标光标继续停留在该元素上方时,该元素的 onclick() 事件应该开始。

换句话说,在 onmouseover() 事件中应该用什么来代替 '.......'?

4

4 回答 4

2
window.countdown = setTimeout(function(){this.click();}, 1000);

此外,您需要清除 mouseout 处理程序中的时间间隔:

clearTimeout(countdown);

理想情况下,你会给你的元素一个 ID 并使用新的事件注册模型:

var e = document.getElementById('myelement');
e.addEventListener('click',function(){
    alert('');
});
e.addEventListener('mouseenter',function(){
    var self = this;
    this.style.color='red';
    window.countdown = setTimeout(function(){self.click();}, 1000);
});
e.addEventListener('mouseleave',function(){
    this.style.color='';
    clearTimeout(countdown);
});
于 2012-12-06T17:18:17.913 回答
1

您应该将鼠标悬停事件的间隔作为全局变量启动,以引用鼠标移出事件以清除它,就像@Asad 说的那样。

<b onclick = "alert()"
 onmouseover = "window.countdown = setTimeout(function(){this.click();}, 1000);"
 onmouseout = "clearTimeout(countdown)">
 123
</b>
于 2012-12-06T17:37:42.463 回答
1

您必须做一些额外的工作,而在内联 Javascript 中这对您来说效果不佳。这都是伪代码,所以我不建议复制/粘贴!

// We'll need to create an interval and store it
var timerInterval = {}
// And keep track of how many seconds have elapsed   
var timeElapsedInSeconds = 0;

function tick (){
   timeElapsedInSeconds++;
   if (timeElapsedInSeconds > 0){
       // YOUR GREAT CODE HERE
   }
   // Either way, let's be sure to reset everything.
   resetTimer();
}

function hoverOverHandler (){
   // Start our timer on hover 
   timerInterval = window.setInterval(tick, 1000);    
}

function resetTimer () {
   timeElapsedInSeconds = 0;
   window.clearInterval(timerInterval);
}

function hoverOutHandler () {
   // Kill timer on hoverout
   resetTimer();
}
于 2012-12-06T17:39:20.757 回答
0

好的,我用动态 id 做了一些技巧,结果如下:

<b style="color:red;" onclick="if(this.style.color!='green'){return false;}else{this.style.color='red';} alert(this.parentNode);" onmouseover="if(this.style.color!='green'){var newID='tmpID_'+Math.floor(Math.random() * (10000000)); if(this.id==''){this.id=newID;} setTimeout('top.document.getElementById(\''+this.id+'\').onclick();',1000); this.style.color='green';}" onmouseout="this.style.color='red';">click</b>

跨浏览 =)

于 2012-12-06T19:36:49.273 回答