jQuery hover事件

hover(over,out)一个模仿悬停事件(鼠标移动到一个对象上面及移出这个对象)的方法。这是一个自定义的方法,它为频繁使用的任务提供了一种“保持在其中”的状态。



  当鼠标移动到一个匹配的元素上面时,会触发指定的第一个函数。当鼠标移出这个元素时,会触发指定的第二个函数。而且,会伴随着对鼠标是否仍然处在特定元素中的检测(例如,处在div中的图像),如果是,则会继续保持“悬停”状态,而不触发移出事件(修正了使用mouseout事件的一个常见错误)。


参数 :

over (Function) : 鼠标移到元素上要触发的函数

out (Function): 鼠标移出元素要触发的函数


示例 :

鼠标悬停的表格加上特定的类


jQuery 代码:


$("td").hover(

function () {

$(this).addClass("hover");

},

function () {

$(this).removeClass("hover");

}

);

实例如下:

<html>

<head>

<style>

body{

font-size:12px;

margin:0px;

}

#box{

width:150px;

margin:auto;

}

.menu{

width:150px;

line-height:25px;

background:#fcc;

}

.level1{

border-color:#fba;

border-style:solid;

border-width:0px1px 1px;

}

ul,li {list-style-type:none;margin:0;padding:0;}

.menuli ul{overflow:hidden; display:none;}

.menuli.level1 a{

display: block;

height: 28px;

line-height: 28px;

color:#42556B;

text-decoration:none;

}

.level2{

background-color:white;


}

.level2li a {

display:block;

height: 28px;

line-height: 28px;

color:#888;

background-color:white;


}

.level2li a:hover {

color:#f00;


}

.current{

overflow:hidden;

background-color:#fba;


}


</style>

<title>jquery导航</title>

<scriptsrc="jquery.js"></script>

<script>

function dropMenu(obj){

$(obj).each(function(){ //遍历当前元素下的每个元素

vartheSpan = $(this);

vartheMenu = theSpan.find(".level2"); //查找类名为".level2"的每个元素

vartarHeight = theMenu.height();

theMenu.css({height:0,opacity:0});

theSpan.hover(

function(){

$(this).addClass("current");

theMenu.stop().show().animate({height:tarHeight,opacity:1},500);

},

function(){

$(this).removeClass("current");

theMenu.stop().animate({height:0,opacity:0},500,function(){

$(this).css({display:"none"});

});

}

);

});

}


$(document).ready(function(){


dropMenu(".level1");


});


</script>

</head>

<body>

<divid="box">

<ulclass="menu">

<liclass="level1"><a href="#">主页</a>

<ulclass="level2">

<li><ahref="#">主页一</a></li>

<li><ahref="#">主页二</a></li>

<li><ahref="#">主页三</a></li>

</ul>

</li>

<liclass="level1"><a href="#">新闻</a>

<ulclass="level2">

<li><ahref="#">新闻一</a></li>

<li><ahref="#">新闻二</a></li>

<li><ahref="#">新闻三</a></li>

</ul>

</li>

<liclass="level1"><a href="#">联系方式</a>

<ulclass="level2">

<li><ahref="#">联系方式一</a></li>

<li><ahref="#">联系方式二</a></li>

<li><ahref="#">联系方式三</a></li>

</ul>

</li>

</ul>

</div>


</body>

</html>

效果图如下: