铺路微光
2016-06-30 23:19
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>className属性</title>
<style>
body{ font-size:16px;}
.one{
border:1px solid #eee;
width:230px;
height:50px;
background:#ccc;
color:red;
}
.two{
border:1px solid #ccc;
width:230px;
height:50px;
background:#9CF;
color:blue;
}
</style>
</head>
<body>
<p id="p1" > JavaScript使网页显示动态效果并实现与用户交互功能。</p>
<input type="button" value="添加样式" onclick="add()"/>
<p id="p2" class="one">JavaScript使网页显示动态效果并实现与用户交互功能。</p>
<input type="button" value="更改外观" onclick="modify()"/>
<script type="text/javascript">
function add(){
var p1 = document.getElementById("p1");
p1.className="one";
}
function modify(){
var p2 = document.getElementById("p2");
p2.className="two";
}
</script>
</body>
</html>
我的理解是object.className是指定元素的class属性,所以id是不可以的,必须要对该元素指定一个class名。然后document.getELementById又是通过ID来获取元素,那么又必须对元素指定一个ID名。所以你就看到了代码中既有ID名,又有class名。说白了ID就是为了让JS获取元素,class是为了让JS对该元素指定或者更改属性
id对应css是用样式选择符“#”(井号);
class对应css是用样式选择符“.”(英文半角输入句号)
你是要控制修改Class,当然不能用#了
JavaScript入门篇
741590 学习 · 9869 问题
相似问题