1、操纵标签style属性
基本语法
标签对像.style.样式名 = 值;
注:小驼峰命名规则书写样式名
例:标签对像.style.fontSize = 值
功能
代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<div id="div1">
<font color="green" size="6">文本内容</font>
</div>
<script type="text/javascript">
var obj1 = document.getElementById("div1");
obj1.style.width = "1000px";
obj1.style.height = "120px";
obj1.style.backgroundColor = "orange";
</script>
</body>
</html>
代码讲解
1、给标签添加样式
var obj1 = document.getElementById(“div1”);
obj1.style.width = “1000px”;
obj1.style.height = “120px”;
obj1.style.backgroundColor = “orange”;
obj1.style.width = “1000px”; 给div添加宽度为1000像素
obj1.style.height = “120px”; 给div添加高度为120像素
obj1.style.backgroundColor = “orange”; 给div添加背景色为桔色
2、操纵标签class属性
基本语法
功能
代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<style type="text/css">
.div1{
width:1000px;
height:200px;
background-color:green;
}
</style>
</head>
<body>
<div id="div1">
<font color="white" size="6">文本内容</font>
</div>
<script type="text/javascript">
var obj1 = document.getElementById("div1");
obj1.className = "div1";
</script>
</body>
</html>
代码讲解
1、给标签添加样式名
var obj1 = document.getElementById(“div1”);
obj1.className = “div1”;
obj1.className = “div1”; 给div 添加样式名为div1
3、this关键字
基本语法
this.className = 类名;
this.style.样式名 = 值;
功能
代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<style type="text/css">
.div1{
width:1000px;
height:200px;
background-color:green;
}
</style>
</head>
<body>
<div id="div1">
<font color="orange" size="6">文本内容1</font>
文本内容2
</div>
<script type="text/javascript">
var obj1 = document.getElementById("div1");
obj1.onclick = function(){
this.className = "div1";
this.style.color = "white";
}
</script>
</body>
</html>
代码讲解
1、给div标签添加click事件
obj1.onclick = function(){
this.className = “div1”;
this.style.color = “white”;
}
obj1.onclick = function() 元素对象添加点击事件
this.className = “div1”; 给当前元素添加类名为div1
this.style.color = “white”; 给当前元素添加文本颜色样式为白色
4、事件冒泡
给父标签和子标签都添加点击事件,当在子标签上方点击后同时也会触法父标签的点击事件,这就是事件冒泡。
基本语法
标签对象.事件名 = function(e){
e.stopPropagation();
}
功能
代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<style type="text/css">
#div1{
width:1000px;
height:200px;
background-color:green;
}
</style>
<script type="text/javascript">
var obj1 = document.getElementById("div1");
obj1.onclick = function(){
alert(1)
}
var obj2 = document.getElementById("font1");
obj2.onclick = function(event){
event.stopPropagation();
alert(2)
}
</script>
</head>
<body>
<div id="div1">
<font color="orange" size="6" id="font1">文本内容1</font>
</div>
</body>
</html>
代码讲解
1、阻止事件冒泡
var obj2 = document.getElementById(“font1”);
obj2.onclick = function(event){
event.stopPropagation();
alert(2);
}
event.stopPropagation(); 在子标签的方法中设置阻止事件冒泡