首页 > 语言 > JavaScript > 正文

JS 实现点击a标签的时候让其背景更换

2024-05-06 15:53:02
字体:
来源:转载
供稿:网友
点击a标签的时候给其换背景的方法有很多,在本文将为大家介绍下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>
<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,否则添加的背景是一整行。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选