利用this属性实现点击按钮变色.选中效果

浏览器宿主的全局环境中,this指的是window对象。

<script type="text/javascript">
    console.log(this === window); //true
</script>

 浏览器中在全局环境下,使用var声明变量其实就是赋值给thiswindow

除了DOM的事件回调或者提供了执行上下文(后面会提到)的情况,函数正常被调用(不带new)时,里面的this指向的是全局作用域。

下面用JavaScript中的this。做一个按钮选中效果,代码如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>按钮变色</title>
		<link rel="stylesheet" href="css/Default style sheet.css" />
	    <style>
	    	#box{
	    		margin: 0px auto;
	    		height: 60px;
	    		width: 600px;
	    		border: 2px solid black;
	    		line-height: 60px;
	    		text-align: center;
	    	}
	    	#box li{
	    		margin-right:10px;
	    		height: 40px;
	    		width: 40px;
	    		border: 1px solid red;
	    		border-radius: 50%;
	            text-align: center;
	           line-height: 40px;
	             float: left;
	     
	    	}
	    .active{
	    	background: olive;
	    	color: blueviolet;
	    	border: 1px solid lightcoral;
	    }	
	    </style>
	<script>
		window.onload=function(){
			var oli=document.getElementsByTagName("li");
			
			for(var i=0;i<oli.length;i++){
				
				oli[i].onclick=function(){
				
			  for(var i=0;i<oli.length; i++){
				  	oli[i].className='';
				  }
				this.className='active';
				}
				
			}
		}
	</script>
	</head>
	<body>
		
		<div id="box">
			<ul>
				<li>1</li>
				<li>2</li>
				<li>3</li>
				<li>4</li>
				<li>5</li>
			</ul>
		</div>
		
		
	</body>
</html>

猜你喜欢

转载自www.cnblogs.com/web928943/p/9999749.html