本章給大家帶來用JS/jquery實現滑鼠事件控制頁面元素顯隱效果,有一定的參考價值,有需要的朋友可以參考一下,希望對你有所協助。
一、mouseout和mouseleave
對於滑鼠指標的移入和移出,就涉及到了mouseover、mouseout和mouseleave事件。
mouseover:當滑鼠指標移到目標元素時觸發該事件;
mouseout:當滑鼠指標移出目標元素或其子項目時,都會觸發該事件;
mouseleave:只有到滑鼠指標移出目標元素時,才會觸發該事件;
這裡需要特別注意mouseout與mouseleave的區別。我們通過下面程式碼範例來看一下:
<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>滑鼠控制頁面元素顯隱</title><script src="http://apps.bdimg.com/libs/jquery/1.11.3/jquery.min.js"></script><style>#boxout,#boxleave {width: 250px;height: 100px;padding-top: 20px;background-color: #cccccc;float: left;margin-left: 30px;}#boxoutson,#boxleaveson {width: 200px;height: 50px;background-color: yellow;padding: 0px auto;margin: 0px auto;}</style></head><body><div id="boxout"><div id="boxoutson">第<span></span>次觸發mouseout事件</div></div><div id="boxleave"><div id="boxleaveson">第<span></span>次觸發mouseleave事件</div></div><script>x = 0;y = 0;$("#boxout").mouseout(function() {$("#boxout span").text(x += 1);});$("#boxleave").mouseleave(function() {$("#boxleave span").text(y += 1);});</script></body></html>
:
二、fadeIn和fadeOut
前文執行個體中用的是show()和hide()方法,前台顯隱效果瞬間完成,為了提高實際使用者體驗,這裡我們介紹兩位更友好的“朋友”,即fadeIn和fadeOut。
fadeIn:方法使用淡入效果來顯示目標元素。
fadeOut:方法使用淡出效果來隱藏目標元素
這兩個方法可以配置參數來控制速度,比如slow、normal、fast或指定毫秒數。
下面我們就show()、hide()與fadeIn()、fadeOut()的效果坐下對比,代碼如下:
<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>滑鼠控制頁面元素顯隱</title><script src="http://apps.bdimg.com/libs/jquery/1.11.3/jquery.min.js"></script><style>#box1,#box2 {width: 250px;height: 100px;padding-top: 20px;background-color: #cccccc;float: left;margin-left: 30px;}#box1son,#box2son {width: 200px;height: 50px;background-color: yellow;padding: 0px auto;margin: 0px auto;}</style></head><body><div id="box1"><div id="box1son"><span>hide和show</span></div></div><div id="box2"><div id="box2son"><span>fadeIn和fadeOut</span></div></div><script>$("#box1 span").hide();$("#box1").mouseover(function() {$("#box1 span").show();}).mouseleave(function() {$("#box1 span").hide();});$("#box2 span").hide();$("#box2").mouseover(function() {$("#box2 span").fadeIn("slow");}).mouseleave(function() {$("#box2 span").fadeOut("slow");});</script></body></html>
滑鼠沒有移動上去的:
滑鼠移動上去的: