gpt4 book ai didi

javascript - 只调用一次函数?

转载 作者:行者123 更新时间:2023-12-01 01:16:09 24 4
gpt4 key购买 nike

所以我在我正在从事的项目中使用了这个 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
}

(可能隐藏在效用函数中。)

关于javascript - 只调用一次函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24874687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com