SetTimeout在jQuery中不能正常工作
SetTimeout does not work correctly in jQuery
这是我的代码。我想让图像在一秒钟后变大,如果我把鼠标放在每个图像上,但是setTimeout
没有响应。即使我把alert()
函数放在menuChanging()
函数的开头,它也会运行,但我的代码的其余部分不会执行(它立即运行,而不是在一秒钟后)。
在鼠标悬停时立即调用函数menuChanging
,相反,您需要将函数引用传递给setTimeout
$(function() {
$(".hormenu > div").hover(function() {
$(this).data('hoverTimer', setTimeout(menuChanging.bind(this), 1000));
}, function() {
var $this = $(this);
//if you move out before 1s then clear the timer
clearTimeout($this.data('hoverTimer'));
//when the mouse is moved out restore to initial state if required
if ($this.hasClass('current')) {
$this.toggleClass("current other").animate({
width: "100px",
opacity: "0.5"
}, 750, 'easeOutBounce');
}
});
});
function menuChanging() {
var duration = 750;
$(".hormenu > .current").not(this).toggleClass("current other").animate({
width: "100px",
opacity: "0.5"
}, duration, 'easeOutBounce');
$(this).removeClass("other").addClass("current").animate({
width: "600px",
opacity: "1"
}, duration, 'easeOutBounce');
}
.hormenu {
height: 500px;
width: 1800px;
}
img {
height: 100%;
width: 100%;
}
.hormenu div {
width: 100px;
overflow: hidden;
display: block;
float: left;
height: 100%;
}
.other {
opacity: 0.5;
}
img {
width: 600px;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<div class="hormenu">
<div class="current">
<img src="http://img0.mxstatic.com/wallpapers/b844e6ef0e3320bc945a9b5b1cd196f9_large.jpeg" alt="" />
</div>
<div class="other">
<img src="http://img0.mxstatic.com/wallpapers/20c41d877dfbed0e52947f51846df781_large.jpeg" alt="" />
</div>
<div class="other">
<img src="http://img0.mxstatic.com/wallpapers/b844e6ef0e3320bc945a9b5b1cd196f9_large.jpeg" alt="" />
</div>
</div>
你可以在这里找到解决问题的方法。
$(function(){
$(".hormenu div").mouseover(
function()
{
setTimeout(menuChanging($(this)),1000);
}
);
});
function menuChanging(div) {
return function(){
var duration = 750 ;
if (!div.hasClass("current")) {
$(".current").removeClass("current").addClass("other").animate({
width: "100px",
opacity: "0.5"
}, duration, 'easeOutBounce');
}
div.removeClass("other").addClass("current").animate({
width: "600px",
opacity: "1"
}, duration, 'easeOutBounce');
}
}
小提琴
您正在调用函数而没有将其传递给setTimeout。我还改变了一些东西,以便轻松检索div。新函数返回一个函数调用,这个新函数可以访问第一个函数的参数。
相关文章:
- Javascript:selenium Web驱动程序isDisplayed()不工作
- jQuery UI自动完成突然停止工作
- AngularJS UI路由器不能像ng路由器那样工作
- HTML5音频加载和播放获胜'我不能在iPad上工作
- JavaScript打印功能使日历停止工作
- Javascript.getHours()工作不正常
- 为什么这在IE中的工作方式与在Firefox中不同
- 视频HTML没有'无法在Internet Explorer 11上工作
- 扩展移相器按钮类不工作
- Firebase迁移-简单的Firebase.set没有'不再工作了——旧的还是新的
- 谷歌地图不是以HTML显示,而是在JS Fiddle上工作
- 正在尝试使用if和else添加类,但无法正常工作
- Jquery FadeIn FadeOut 只工作一次
- Foreach无法在Typescript中工作
- 另一个ajax调用中的Jquery ajax调用在for循环中没有按预期工作
- 为什么不是't窗口.恢复正常工作吗?(javascript/jquery)
- JS可以在Chrome中工作,但不能在Firefox中工作
- 最大高度转换不;不工作,工作缓慢
- Gulp-rev:不是第一次工作,而是在第一次工作之后工作
- JQuery - Ajax: encodeUriComponent不工作(EncodeUri工作)