[英]SetTimeout does not work correctly in jQuery
這是我的代碼 。 我希望如果我將鼠標放在每個圖像上一秒鍾后圖像變大,但是setTimeout
沒有響應。 即使我在menuChanging()
函數的開頭放置了alert()
函數,它menuChanging()
運行,但其余代碼不會執行(它立即運行,而不是一秒鍾后運行)。
您正在調用功能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。 新函數返回一個要調用的函數,該新函數可以訪問第一個參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.