onmouseover()在1秒后调用onclick?

时间:2012-12-06 17:15:48

标签: javascript html events onmouseover onmouseout

我有一个元素:

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

我需要当元素被鼠标移过时,1秒后鼠标光标继续停留在此元素之上,然后onclick()此元素的事件应该开始。

换句话说,在onmouseover()事件中应该是什么而不是'..............'?

4 个答案:

答案 0 :(得分: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);
});

答案 1 :(得分:1)

你应该将鼠标悬停事件的间隔作为全局变量开始,以引用鼠标输出事件来清除它,就像@Asad所说的那样。

<b onclick = "alert()"
 onmouseover = "window.countdown = setTimeout(function(){this.click();}, 1000);"
 onmouseout = "clearTimeout(countdown)">
 123
</b>

答案 2 :(得分: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();
}

答案 3 :(得分: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>

crossbrowsered =)