现在的位置: 首页 > 综合 > 正文

JS 实现点击 标签的时候给其换背景

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type=text/javascript src="alabel.js"></script>
<style type="text/css">
.curr{background:blue;display:inline;}
</style>

</head>
<body>
<div class="">
 <span><a href="#">1</a></span>
</div>

</body>
</html> 

在alabel.js中:

window.onload = function ()
{
 var aspan = document.getElementsByTagName("span");
 var i = 0; 
 for (i = 0; i < aspan.length; i++)
 {  
  aspan[i].onclick = function ()
  {
   for (i = 0; i < aspan.length; i++) aspan[i].className = "";
   this.className = "curr";
  };
 }
};

这样就可以实现在点击a标签的时候给其添加红色的背景。

注意:curr的属性中display不能是block,否则添加的背景是一整行。

抱歉!评论已关闭.