zoukankan      html  css  js  c++  java
  • JS添加、设置属性以及鼠标移入移出事件

    源代码:

    <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="UTF-8">
    		<title></title>
    		<style type="text/css">
    			*{
    				margin: 0px auto;
    			}
    			#wk{
    				100px;
    				
    			}
    			.pname{
    				 100px;
    				height: 50px;
    				line-height: 50px;
    				text-align: center;
    				background-color: yellow;
    				margin: 2px ;
    				
    			}
    		</style>
    	</head>
    	
    	<body>
    		<div id="wk">
    			<div class="pname" onmouseover="ChangeColor(this)"
    								onclick="ClickChange(this)"
    								onmouseout="KeepColor(this)">
    				小花
    			</div>
    			<div class="pname" onmouseover="ChangeColor(this)"
    								onclick="ClickChange(this)"
    								onmouseout="KeepColor(this)">
    				小白
    			</div>
    			<div class="pname" onmouseover="ChangeColor(this)"
    								onclick="ClickChange(this)"
    								onmouseout="KeepColor(this)">
    				小明
    			</div>
    			
    		</div>
    	</body>
    	<script type="text/javascript">
    		//获取要改变样式的元素
    		var pname = document.getElementsByClassName("pname");
    		
    		
    		//鼠标点击事件,移入变色
    		function ClickChange (a) {
    			for (var i=0; i<pname.length; i++) {
    				
    				//移除属性 a
    				pname[i].removeAttribute("a");
    				//背景色初始化
    				pname[i].style.backgroundColor = "yellow";
    			}
    			//为变色元素添加属性a
    			a.setAttribute("a",1);
    			//鼠标移入,改变背景色
    			a.style.backgroundColor = "red";
    		}
    		
    		//鼠标移入事件,点击改变背景色
    		function ChangeColor (a) {
    			//循环添加背景色
    			for (var i=0; i<pname.length; i++) {
    				//清样式
    				if (pname[i].getAttribute("a")!=1){
    					pname[i].style.backgroundColor ="yellow";
    				} 
    				
    			}
    			a.style.backgroundColor = "red";
    		}
    		
    		//添加鼠标移出事件
    		function KeepColor(a) {
    			
    			for (var i=0; i<pname.length; i++) {
    				//清样式
    				if (pname[i].getAttribute("a")!=1)
    				{
    					
    					pname[i].style.backgroundColor ="yellow";
    				} 
    				
    			}
    		}
    	</script>
    </html>
    

      效果如下:

  • 相关阅读:
    关于这个 blog
    P6499 [COCI2016-2017#2] Burza 题解
    CF1172F Nauuo and Bug 题解
    CF1479D Odd Mineral Resource 题解
    CF1442E Black, White and Grey Tree 题解
    CF1442D Sum 题解
    CF1025D Recovering BST 题解
    CF1056E Check Transcription 题解
    CF1025F Disjoint Triangles 题解
    红包算法的PHP实现
  • 原文地址:https://www.cnblogs.com/davis16/p/8379364.html
Copyright © 2011-2022 走看看