zl程序教程

您现在的位置是:首页 >  前端

当前栏目

jQuery mouseover和mouseout事件

jQuery事件 mouseout
2023-06-13 09:12:02 时间
当用户将鼠标指针移到某个元素上时,就会触发 mouseover 事件。当用户将鼠标指针移出某个元素时,就会触发 mouseout 事件。mouseover 和 mouseout 平常都是形影不离的。

mouseover 和 mouseout 分别用于控制鼠标指针 移入 和 移出 这两种状态。例如,在下拉菜单导航中,鼠标指针移入会显示二级导航,鼠标指针移出则会收起二级导航。

举例:移入和移出


 !DOCTYPE html 

 html 

 head 

 meta charset= utf-8 / 

 title /title 

 script src= js/jquery-1.12.4.min.js /script 

 script 

 $(function () {

 $( div ).mouseover(function(){

 $(this).css( color , red 

 $( div ).mouseout(function () {

 $(this).css( color , black 

 /script 

 /head 

 body 

 div C语言中文网 /div 

 /body 

 /html 

预览效果如图 1 所示。

鼠标指针移入和移出
图 1:鼠标指针移入和移出

这里的$(this) 指的其实就是触发当前事件的元素,也就是 div 元素。在这个例子中,$(this)等价于$( div )。$(this)的使用是非常复杂的,这里我们只是让初学者熟悉一下,后面再给小伙伴们详细讲解。

上面这个例子虽然简单,但是方法已经教给大家了。大家可以尝试使用 mouseover 和 mouseout 这两个事件来设计下拉菜单效果。

举例:链式调用


 !DOCTYPE html 

 html 

 head 

 meta charset= utf-8 / 

 title /title 

 script src= js/jquery-1.12.4.min.js /script 

 script 

 $(function () {

 $( div ).mouseover(function(){

 $(this).css( color , red 

 }).mouseout(function () {

 $(this).css( color , black 

 /script 

 /head 

 body 

 div C语言中文网 /div 

 /body 

 /html 

预览效果如图 2 所示。

链式调用
图 2::链式调用

分析:


$( div ).mouseover(function(){

 $(this).css( color , red 

}).mouseout(function () {

 $(this).css( color , black 

})

上面的代码其实等价于:


$( div ).mouseover(function(){

 $(this).css( color , red 

$( div ).mouseout(function () {

 $(this).css( color , black 

})

在 jQuery 中,如果对同一个对象进行多种操作,则可以使用链式调用的语法。链式调用是 jQuery 中的经典语法之一,不仅可以节省代码量,还可以提高代码的性能和效率。

23823.html

CSSC语言htmljavaJavaScript