在学JS的时候,大家还记得有两个方法叫移入移出事件吗?onmouseover()与onmouseout()事件~
jQuery当中同样提供了这样的事件来监听用户的移入移出操作,mouseover()与mouseout()事件,两者用法类似,下面一mouseover为例:
方法一:$ele.mouseover()
绑定$ele元素,不带任何参数一般是用来指定触发一个事件,用的比较少
<div id="test">点击触发<div>
$("ele").mouseover(function(){
alert('触发指定事件')
})
$("#test").click(function(){
$("ele").mouseover() //指定触发事件
});
方法二:$ele.mouseover( handler(eventObject) )
绑定$ele元素,每次$ele元素触发点击操作会执行回调 handler函数
这样可以针对事件的反馈做很多操作了
<div id="test">滑动触发<div> $("#test").mouseover(function() { //this指向 div元素 });
方法三:$ele.mouseover( [eventData ], handler(eventObject) )
使用与方法二一致,不过可以接受一个数据参数,这样的处理是为了解决不同作用域下数据传递的问题
<div id="test">点击触发<div> $("#test").mouseover(11111,function(e) { //this指向 div元素 //e.data => 11111 传递数据 });
具体使用可以参考右边的代码
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title></title> <style> .left div, .right div { width: 350px; height: 150px; padding: 5px; margin: 5px; border: 1px solid #ccc; } p{ height: 50px; border: 1px solid red; margin: 30px; } .left div { background: #bbffaa; } .right div { background: yellow; } </style> <script src="https://www.imooc.com/static/lib/jquery/1.9.1/jquery.js"></script> </head> <body> <h2>mouseover与mouseout事件</h2> <h4>测试一</h4> <button>点击:指定触发mouseover事件</button> <script type="text/javascript"> $('h2').mouseover(function(e) { alert('触发h2元素绑定的mouseover') }) $("button:eq(0)").click(function(e) { $('h2').mouseover() //指定触发绑定的事件 }) </script> <h4>测试二</h4> <div class="left"> <div class="aaron1"> <p>鼠标移进此区域触发mouseover事件</p> <a>进入元素内部,mouseover事件触发次数:</a> </div> </div> <script type="text/javascript"> var n = 0; //绑定一个mouseover事件 $(".aaron1 p:first").mouseover(function(e) { $(".aaron1 a").html('进入元素内部,mouseover事件触发次数:' + (++n)) }) </script> <h4>测试三</h4> <div class="right"> <div class="aaron2"> <p>鼠标移动:不同函数传递数据</p> <a>进入元素内部,mouseover事件触发次数:</a> </div> </div> <br/> <script type="text/javascript"> var n = 0; //不同函数传递数据 function data(e) { $(".right a").html('mouseover事件触发次数:' + (++n) + '<br/> 传入数据为 :'+ e.data) } function a() { $(".right p:first").mouseover('data = 慕课网', data) } a(); </script> </body> </html>