gpt4 book ai didi

javascript - jQuery 语法、鼠标悬停和超时

转载 作者:行者123 更新时间:2023-11-28 07:50:37 25 4
gpt4 key购买 nike

我第一次使用 JQuery,并尝试为一个元素实现脚本,该元素将“鼠标输入”扩展至 50px。鼠标悬停 1 秒或更长时间后,它应该进一步扩大到 190 像素。最后,当鼠标离开该位置时,其大小应重新调整回 35 像素。如果鼠标在完全扩展到 190 像素之前离开该位置,则不应继续执行该步骤。

到目前为止,我开发的代码允许元素展开,但如果鼠标被移除,则无论悬停时间如何,元素的大小都会达到 190px。

我意识到我很可能需要在这里使用超时函数或某种 if 语句,但是我在将其添加到原始代码中时遇到问题;

   $(document).ready(function() {
$("#element").on("mouseenter", function() {
$(this).animate({"width": "50px"})
//DELAY 100MS, IF THE MOUSE IS STILL HOVERED THEN PROCEED
.animate({"width": "190px"});
//ELSE CONTINUE WITH MOUSE LEAVE FUNCTION
}).on("mouseleave", function() {
$(this).animate({"width": "35px"});
});
});

就像我提到的,我很难找到正确的语法,并且在阅读其他问题后我变得更加困惑;哪个最好用?超时、.hover、if 语句等?

http://jsfiddle.net/#&togetherjs=3gl8z3blFI

最佳答案

尝试在第二个动画之前使用 setTimeout 函数设置 1 秒超时:

$("#element").on("mouseenter", function () {
$(this).animate({width: 50});
$(this).data('hover-timeout', setTimeout(function() {
$(this).animate({width: 190});
}.bind(this), 1000));
})
.on("mouseleave", function () {
clearTimeout($(this).data('hover-timeout'));
$(this).stop(true).animate({width: 35});
});
#element {
background-color: #AAA;
width: 35px;
height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="element"></div>

关于javascript - jQuery 语法、鼠标悬停和超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26854327/

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