跳到主要內容

解決mouseenter及mouseleave執行物件動畫未完成又重複觸發的問題-教學撰寫:徐嘉裕Neil hsu

如果要用jQuery的mouseenter(滑鼠滑入)及mouseleave(滑鼠滑出)來執行物件動畫,會遇到一個問題,假使mouseenter時物件因該要跑到left:80px的位置才算動畫完成,mouseenter則回到left:0px的位置,但在動畫未執行完成user又快速的在執行區塊滑入滑出,就會變成動畫亂跳的情況!!

舉例來說,像下面這張圖三個物件是尚未mouseenter觸發前的狀態



滑鼠滑入其中一個按鈕會觸發mouseenter動畫事件,物件往左上移動



滑鼠滑出執行區會觸發mouseleave動畫事件,物件往右下移動,返回原本位置




js-code應該是這樣

//mouseenter
$("body").on("mouseenter", "#indexblocksbox01", function (){
$(this).css("cursor", "pointer");
$(this).css({"animation-name":"indexbox1","animation-duration":"0.4s","left":"160px","top":"53px"});
$("#title01btn").css({"animation-name":"indexbox2","animation-duration":"0.4s","background-color":"#FFFFFF","color":"#E77C00"});
})

//mouseleave
$("body").on("mouseleave", " #indexblocksbox01", function (){
$(this).css("cursor", "auto");
$(this).css({"animation-name":"indexbox3","animation-duration":"0.6s","left":"200px","top":"93px"});
$("#title01btn").css({"animation-name":"indexbox4","animation-duration":"0.8s","background-color":"transparent","color":"#FFFFFF"});
})


但如果滑鼠快速的在物件切換就會導致物件動畫重複被執行,一直由開始處跳動狀態,非常奇怪!

解決方法,就是mouseenter->取mouseleave的css結束值來做判斷,同樣mouseleave->取mouseenter的css結束值來做判斷,這樣設定後動畫必須要執行完畢到結束位置才會觸發新的動畫效果,也不會亂跑亂跳了,方法如下:

//mouseenter
$("body").on("mouseenter", "#indexblocksbox01", function (){
$(this).css("cursor", "pointer");
if($(this).css("left")=="200px"){  //取mouseleave的lfet位置做判斷
$(this).css({"animation-name":"indexbox1","animation-duration":"0.4s","left":"160px","top":"53px"});
$("#title01btn").css({"animation-name":"indexbox2","animation-duration":"0.4s","background-color":"#FFFFFF","color":"#E77C00"});
}
})

//mouseleave
$("body").on("mouseleave", "#indexblocksbox01", function (){
$(this).css("cursor", "auto");
if($(this).css("left")=="160px"){  //取mouseenter的lfet位置做判斷
$(this).css({"animation-name":"indexbox3","animation-duration":"0.6s","left":"200px","top":"93px"});
$("#title01btn").css({"animation-name":"indexbox4","animation-duration":"0.8s","background-color":"transparent","color":"#FFFFFF"});
}
})

當然也不一定要用left判斷,只要是動畫中任何的css結束設定值都可以,這樣才能讓動畫完整跑完,增加user操作視覺舒適感,有需要的朋友參考看看


工作心得撰寫:徐嘉裕 Neil hsu

留言