Home  >  Article  >  Web Front-end  >  JavaScript动态设置div的样式的方法_javascript技巧

JavaScript动态设置div的样式的方法_javascript技巧

WBOY
WBOYOriginal
2016-05-16 15:23:171219browse

有时候需要根据需要动态设置div的样式,当然对于稍有经验的javascript开发者来说,这一切都是那么的简单,但是对于初学者或者说没有相关经验的开发者来说可能就是一个不大不小的难关,下面就通过实例简单介绍一下如何实现此效果。

代码实例如下:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<head>
<title>动态设置div的样式</title>
<style type="text/css">
div{
 width:50px;
 height:50px;
 background:red;
 margin-top:10px;
}
.bg{
 background-color:blue;
}
</style>
<script type="text/javascript">
window.onload=function(){
 var firstDiv=document.getElementById("firstDiv");
 var secondDiv=document.getElementById("secondDiv");
 var first=document.getElementById("first");
 var second=document.getElementById("second");
 first.onclick=function(){
   firstDiv.style.backgroundColor="green";
 }
 second.onclick=function(){
   secondDiv.className="bg";
 }
}
</script>
</head>
<body>
<div id="firstDiv"></div>
<div id="secondDiv"></div>
<input type="button" value="使用style方式" id="first" />
<input type="button" value="使用className方式" id="second" />
</body>
</html> 

以上代码实现了我们的要求,不过是用了两种方法,一种是style方式,一种是className方式。

特别注意:

1.使用style时,像background-color这种符合单词属性要使用驼峰写法(第二个单词首字母大写),写成backgroundColo这种形式。

2.使用className时,属性值是class样式名称,但是前面不能加点(.)。

PS:JavaScript动态改变div属性的实现方法

本文实例讲述了JavaScript动态改变div属性的实现方法。分享给大家供大家参考。具体如下:

这里可以通过JS动态改变div属性,样式等

<script type="text/javascript">
 var oBox = document.getElementById('box');
 var oDiv = document.getElementById('div1');
 var aInput = document.getElementsByTagName('input');
 var aAttr = ['width', 'height', 'backgroundColor', 'display', 'display'];
 var aValue = ['200px', '200px', 'red', 'none', 'block'];
 for(var len=aInput.length,i=0;i<len;i++){
  aInput[i].index = i; //索引
  aInput[i].onclick = function(){
   //重置按钮,cssText清空DIV属性
   if(this.index == aInput.length - 1)oDiv.style.cssText = "";
   //设置DIV属性
   property(oDiv, aAttr[this.index], aValue[this.index]);
  };
 }
 //控制DIV属性
 function property(obj, attr, value){
  obj.style[attr] = value;
 }
</script>

希望本文所述对大家的javascript程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn