2011-05-18 179 views
4
function hoverOpacity() { 
    $('#fruit').mouseover(function() { 
     $(this).animate({opacity: 0.5}, 1500); 
     }); 
    $('#fruit').mouseout(function() { 
     $(this).animate({opacity: 1}, 1500); 
     }); 
} 

這是我的功能,動畫div#fruit,它它的工作。jQuery鼠標懸停鼠標不透明

問題是這樣的;當您在mousein動畫完成之前mouseout時,它必須在開始mouseout之前完成動畫。 (希望有道理)

這通常不明顯,但持續時間很長,這是顯而易見的。

我不想完成動畫,而是要停止動畫並將其轉換回原始狀態。

+2

感謝您的答覆的每個人。 停止功能導致我到以下頁面,這正是我需要的掃描笏: http://css-tricks.com/examples/jQueryStop/ – 2011-05-18 11:03:31

回答

1

試試這個:

function hoverOpacity() { 
    $('#fruit').mouseover(function() { 
     $(this).stop(true, true).animate({opacity: 0.5}, 1500); 
     }); 
    $('#fruit').mouseout(function() { 
     $(this).stop(true, true).animate({opacity: 1}, 1500); 
     }); 
} 

這應該停止動畫,清除隊列(第一個參數),並跳轉到結束(第二ARG),你可以用參數適當改變周圍/一塌糊塗。

2

您需要添加一個調用.stop()您動畫之前清除當前和任何排隊的動畫:

function hoverOpacity() { 
    $('#fruit').mouseover(function() { 
     $(this).stop(true).animate({opacity: 0.5}, 1500); 
     }); 
    $('#fruit').mouseout(function() { 
     $(this).stop(true).animate({opacity: 1}, 1500); 
     }); 
} 
5

您正在尋找的stop功能,可能還跟着show(或hide,或css ,取決於你想要什麼狀態opacity結束)。

function hoverOpacity() { 
    $('#fruit').mouseover(function() { 
     $(this).stop(true).animate({opacity: 0.5}, 1500); 
     }); 
    $('#fruit').mouseout(function() { 
     $(this).stop(true).animate({opacity: 1}, 1500); 
     }); 
} 

true告訴動畫跳轉到最後。如果這是該元素上唯一的動畫,則應該沒問題;否則,如我所說,你可以看看css明確設置所需的不透明度。

另外,雖然,你可能看使用mouseentermouseleave而不是mouseovermouseout,原因有二:1,mouseover重複橫跨該元素的鼠標移動,和2都mouseovermouseout泡沫和所以如果你的「水果」元素有子元素,你也會接收到它們的事件,這往往會破壞這種動畫的穩定性。

+0

是的,我正在尋找.stop功能,謝謝:) – 2011-05-18 11:00:13

+0

@a -second-mix:另請參閱關於可能使用不同事件的說明。 – 2011-05-18 11:01:05

0

試試這個藏漢:

function hoverOpacity() { 
    $('#fruit').hover(function() { 
     $(this).animate({opacity: 0.5}, 1500); 
    }, function() { 
     $(this).animate({opacity: 1}, 1500); 
    }); 
} 
+0

添加「.stop()」以及... – metaforce 2011-05-18 10:58:24