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>
    

      效果如下:

  • 相关阅读:
    linux:shell:tree
    html5,css3
    asp.net web forms page life cycle
    Unobtrusive Javascript
    Multitier architecture
    C#接口的显示实现和隐式实现
    Modernizr
    android w700
    debian e42 wifi
    mstest run dll
  • 原文地址:https://www.cnblogs.com/davis16/p/8379364.html
Copyright © 2011-2022 走看看