javascript动态改变元素css样式简单介绍

快乐打工仔 分类:实例代码

使用js动态修改元素的css样式的方式有很多种,下面就通过代码实例做一下简单介绍。

一.修改元素的style属性值:

这种方式能够给样式最高的权重,直接在元素上修改style属性。

代码实例如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>前端教程网</title>
<style type="text/css">
#antzone{
  width:200px;
  height:100px;
  background:green;
}
</style>
<script type="text/javascript">
window.onload=function(){
  var obt=document.getElementById("bt");
  var odiv=document.getElementById("antzone");
  obt.onclick=function(){
    odiv.style.backgroundColor="red";
  }
}
</script>
</head>
<body>
<div id="antzone"></div>
<input type="button" id="bt" value="查看效果"/>
</body>
</html>

上面的代码演示了相关的方式,非常的简单。

特别说明:如果遇到background-color或者font-size这种复合属性,需要使用驼峰写法,不能够在使用中横岗了,因为这个在javascript中是表示减。

二.更改元素的class属性:

使用className属性就可以实现此功能。

代码实例如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>前端教程网</title>
<style type="text/css">
#antzone{
  width:200px;
  height:100px;
  background:green;
}
.softwhy{
  border:1px solid blue;
}
</style>
<script type="text/javascript">
window.onload=function(){
  var obt=document.getElementById("bt");
  var odiv=document.getElementById("antzone");
  obt.onclick=function(){
    odiv.className="softwhy";
  }
}
</script>
</head>
<body>
<div id="antzone"></div>
<input type="button" id="bt" value="查看效果"/>
</body>
</html>

上面的代码就可以为元素添加名为softwhy的class属性值。

如果想要删除的class样式类可以参阅js如何动态删除class样式属性值中的指定样式类一章节。

回复

我来回复
  • 暂无回复内容