為什么按鈕沒有效果?。。?!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標(biāo)題文檔</title>
<style type="text/css">
body{margin:0;padding:0;}
.song1{ width:200px; font:16px "微軟雅黑",sans-serif; background:#CF6; margin:20px auto;}
.song2{ width:200px; font:16px "微軟雅黑",sans-serif; background:#CCC; margin:50px auto; padding:20px;}
.btn{margin:0 auto; width:200px;}
</style>
<script type="text/javascript">
var c=document.getElementById("song");
//隱藏
function btnNone()
{
c.style.display="none";
}
//顯示
function btnShow()
{
c.style.display="block";
}
//更換css樣式
function btnClass()
{
c.className="song2";
}
//增加
function btnAdd()
{
}
//去除所有的js樣式
function btnRem()
{
c.removeAttribute("style");
}
</script>
</head>
<body>
<div ?id="song" class="song1">哀怨斷腸》,胡偉立的《市集》、《笑傲江湖曲(琴簫合奏)》,麥振鴻的《景天——護(hù)甲》、《雪見——仙凡之旅》、《莫失莫忘》、《長留山》、《癡顏》、《只相信你(不可說)》、《疤痕》</div>
<br/>
<hr/>
<div class="btn">
<input type="button" value="隱藏" onclick="btnNone()"/>
<input type="button" value="顯示" onclick="btnShow()"/>
<input type="button" value="換裝" onclick="btnClass()"/>
<input type="button" value="增加" onclick="btnAdd()"/>
<input type="button" value="恢復(fù)出廠設(shè)置" onclick="btnRem()"/>
</div>
</body>
</html>
2016-05-12
謝謝!
2016-05-12
html文檔是自上而下加載的,加載到一個節(jié)點(diǎn)就渲染一個,加載到css、js文件就執(zhí)行。所以有時(shí)候會看到網(wǎng)頁上面已經(jīng)有內(nèi)容,底部還是空白。或者網(wǎng)速慢的時(shí)候,會看到頁面沒有樣式。以你的代碼來說,如果js代碼在前,節(jié)點(diǎn)<div id=song>在后,則,執(zhí)行js代碼的時(shí)候,網(wǎng)頁中還不存在,所以會得到c為nul或obj2為空集合。
而如果這樣
與要獲取id的位置有關(guān),而和在Button的前后沒有關(guān)系
2016-05-11
與<script>標(biāo)簽的位置有關(guān),var c=document.getElementById("song");只能獲取到該代碼以前的標(biāo)簽。你可以把<script>......</script>部分放到
<div class="btn">
<input type="button" value="隱藏" onclick="btnNone()"/>
<input type="button" value="顯示" onclick="btnShow()"/>
<input type="button" value="換裝" onclick="btnClass()"/>
<input type="button" value="增加" onclick="btnAdd()"/>
<input type="button" value="恢復(fù)出廠設(shè)置" onclick="btnRem()"/>
</div>
的后邊。