函數內部沒有獲取p1、p2節點,為何能夠設置class屬性
<!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>
2016-06-27
?p1.className = "one";
?p2.className = "two";
這兩句就可以獲取class屬性,因為本文將變量名和樣式名寫成一樣的,所以很多人看著很繞,這里的p1和p2被認為是元素id了,所以才能設置元素,但實際上我們的認為是變量。建議你將變量給修改,就知道結果了
2016-03-27
可能是緩存問題
2016-03-20
var p1 = document.getElementById("p1");
?var p2 = document.getElementById("p2");這兩段語句是通過ID獲取了P1和P2的元素,如何然后再去修飾元素。