本文介绍JavaScript动态改变div样式的两种常用方法。通过实例演示如何使用style对象直接修改CSS属性,包括驼峰命名规则;以及如何通过修改className属性切换预设样式类。文章涵盖具体代码实现及注意事项,帮助开发者掌握前端动态样式控制的技巧。
JavaScript动态设置div样式的两种方法:style与className
在实际开发中,经常需要根据用户交互或数据状态动态调整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属性来应用预设的CSS类。
需要特别注意以下关键点:
1. 当使用style对象直接修改CSS属性时,对于包含连字符的属性名(如background-color),必须采用驼峰命名法(CamelCase),即将连字符移除并将后续单词的首字母大写,例如写作backgroundColor。
2. 当使用className属性时,其值应为CSS样式类的名称字符串,且该字符串中不能包含类选择器的点号(.)前缀。
补充说明:JavaScript动态改变div属性的实现方法
本实例详细讲解了利用JavaScript动态修改div属性及样式的具体实现方式,供读者参考学习。
通过JavaScript脚本,可以动态地改变div元素的各类属性及视觉样式。
JS修改div样式:style对象与className用法详解
<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程序设计的开发者有所帮助。