2013-02-19 38 views
3

鼠標兩秒後,但設置超時功能無法正常工作鼠標,則可以將超時功能未在工作

JS

setTimeout(function() { 
    $('.box').mouseover(function() { 
    $(this).animate({ 
     marginTop: '-224px', 
     height: '300px' 
    }) 
    $(this).find('.rotate-arrow').addClass('rotate'); 
    }); 
}, 2000); 

回答

6

說明:

您已連接setTimeout內部的事件處理函數基本上意味着它將等待2秒鐘,然後將函數附加到.box元素的mouseover

不幸的是,來自setTimeout函數的$(this)超出了範圍,因此您的值未被讀取。幸運的是,您可以簡單地將$(this)分配給中的變量嵌套函數的範圍,您可以像平常那樣訪問jquery對象。


解決方案:

$('.box').mouseover(function() { 
    var $this = $(this) 
    setTimeout(function() { 
    $this.animate({ marginTop: '-224px', height: '300px' }) 
    $this.find('.rotate-arrow').addClass('rotate'); 
    }, 2000); 
}); 

的jsfiddle:

+0

來優化代碼(避免重複jquery元素換行):在mouseover函數內添加'var $ this = $(this)'並在setTimeout中用'$ this'替換'$(this)'' – alexbusu 2013-02-19 09:18:31

+0

謝謝,但它顯示無法讀取屬性高度 – Prashobh 2013-02-19 09:18:54

+0

@prash對不起,請嘗試新代碼 – 2013-02-19 09:19:34