鼠标悬停为子div添加class

本文介绍了一种使用jQuery实现鼠标悬停时更改子div样式的HTML页面示例。通过为每个子div单独绑定mouseover和mouseout事件,当鼠标悬停在子div上时为其添加特定样式,并在移除时还原初始样式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!-- 
author:IluckySi
since:20150331
功能:一个父div下面有多个子div,如何实现鼠标悬停到子div上面,子div添加class.
 -->
<!DOCTYPE html>
<html>
  <head>
    <title>mouse.html</title>
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <style>
    	.child {
    		width:100px;
    		height:100px;
    		background-color:red
    	}
    	.currentChild {
    		width:120px;
    		height:120px;
    		background-color:black
    	}
    </style>
    <script src="../../jquery/jquery-1.11/jquery.min.js"></script>
    <script>
    $(function() {
    	//获取所有子div.
    	var children = $('div#parent > div');
    	
    	//错误方法:会给所有子div添加class.
    	/* children.mouseover(function(e) {
    		children.addClass('currentChild');
    	}).mouseout(function(e) {
    		children.removeClass('currentChild');
    	});  */
    	
    	//正确方法:通过each为每个子div添加class.
    	children.each(function(i){
    		//注意:this是js对象,$(this)是jquery对象.
	   		$(this).mouseover(function(e) {
	   			$(this).addClass('currentChild');
	       	}).mouseout(function(e) {
	       		$(this).removeClass('currentChild');
	       	});
   		}); 
    });
    </script>
  </head>
  <body>
    <div id="parent">
    	<div class="child">A</div><hr>
    	<div class="child">B</div><hr>
    	<div class="child">C</div><hr>
    	<div class="child">D</div><hr>
    	<div class="child">E</div><hr>
    </div>
  </body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值