[英]Only call function once?
所以我在我正在研究的项目上有这个javascript:
<script type="text/javascript">
document.getElementById('contact').onmouseover = function ()
{
var w = 130;
function step()
{
if (w < 250)
{
middle.style.width = (w++) + "px";
setTimeout(step, 5);
}
}
setTimeout(step, 1500);
};
</script>
我希望这只运行一次。 在检测到鼠标悬停后,我希望它运行该功能,然后再次运行,直到页面刷新。 我怎么做到这一点?
我要么使用jQuery的one
方法,要么你想使用'普通'JavaScript,你可以在触发函数后删除事件。 这是一个例子:
// Create a named function for the mouseover event
function myFunc() {
// Remove the `myFunc` function event listener once `myFunc` is run
document.getElementById('contact').removeEventListener('mouseover', myFunc, false);
var w = 130;
function step() {
if (w < 250) {
middle.style.width = (w++) + "px";
setTimeout(step, 5);
}
}
setTimeout(step, 1500);
};
// Add an event listener to run the `myFunc` function on mouseover
document.getElementById('contact').addEventListener('mouseover', myFunc, false);
注意,如果你必须支持IE8(甚至更早),你需要使用...attachEvent("onmouseover", myFunc)
和detachEvent("onmouseover", myFunc);
代替; 你可以通过检查元素是否有addEventListener
来判断:
var elm = document.getElementById('contact')
if (elm.addEventListener) {
// Use addEventListener
}
else {
// Use attachEvent
}
(也许隐藏在实用功能中。)
您需要做的就是从侦听器中删除事件侦听器(以便它将停止侦听事件)。 但是,为了删除侦听器,您需要对它进行引用,因此您无法使用直接连接到mouseover
的预定义侦听器来执行此操作。 相反,使用addEventListener
来附加侦听器,保留返回的引用,然后使用removeEventListener
从回调中删除侦听removeEventListener
。
var contact = document.getElementById('contact');
contact.addEventListener('mouseover', tehlistener);
function tehlistener() {
// yada yada do whatever
// ...
// I think it's ok to use `this` here, but since this is so specific
// its better to be specific about which listener you want removed
contact.removeEventListener('mouseover', tehlistener);
};
这是关于addEventListener的可爱MDN文章的链接。
如果您对使用JQuery感兴趣,那么有一个很好的函数称为“one”,可能正是您所需要的。
编辑:添加更多代码以显示更多解决方案:
$( "#contact" ).one( "mouseover", function() {
var w = 130;
function step()
{
if (w < 250)
{
middle.style.width = (w++) + "px";
setTimeout(step, 5);
}
}
setTimeout(step, 1500);
});
您可以使用once
功能。
function once(fn){
var called = false;
return function(){
if (called) {
return;
}
called = true;
return fn.apply(this, arguments);
}
}
例:
something.onmouseover = once(function(){
// this will happen only once
});
你可以只覆盖事件处理程序
<script type="text/javascript">
document.getElementById('contact').onmouseover = function() {
var w = 130;
function step() {
if (w < 250) {
middle.style.width = (w++) + "px";
setTimeout(step, 5);
}
}
setTimeout(step, 1500);
this.onmouseover = null;//overwrite event handler with a blank callback
};
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.