為什么這里JS代碼的位置只能放在最后?
<!DOCTYPE?html> <html> <head>?? <meta?charset="UTF-8">?? <meta?name="viewport"?content="width=device-width,?initial-scale=1.0">?? <meta?http-equiv="X-UA-Compatible"?content="ie=edge">?? <title>顯示與隱藏</title>? <style?type="text/css">?? ??body{font-size:?12px;}?? ??#txt{height:?400px;width:?600px;border:?1px?solid?#333;padding:?5px;}? ??p{line-height:?18px;text-indent:2em;}?? </style> </head> <body>? ?<h2?id="con">JSSENIE</h2>?? ?<div?id="txt">?? ??<h5>主要內(nèi)容</h5>??? ??<p>主要內(nèi)容1</p><p>主要內(nèi)容2</p><p>主要內(nèi)容3</p>? ?</div>?? <form?>?? ??<input?type="button"?value="change?color"?onclick="changecolor()">????? ??<input?type="button"?value="change?size"?onclick="changesize()">?????? ??<input?type="button"?value="hide?text"?onclick="hide()">????????? ??<input?type="button"?value="show?text"?onclick="show()">???????????? ??<input?type="button"?value="reset?all"?onclick="resetall()">? </form>? <script?type="text/javascript">?? ?var?content=document.getElementById('txt');? ??function?changecolor(){?? ????content.style.color="red";??? ????content.style.backgroundColor="#ccc";??}? ??function?changesize(){?content.style.width="200px";?content.style.height="200px";}? ??function?hide(){?content.style.display="none";}? ??function?show(){?content.style.display="block";}? ??function?resetall(){?? ?????var?mychose=confirm("你確定重置嗎?");?? ?????if?(mychose==true){?????? ??????content.removeAttribute("style")??? ??????}? ?????}? </script> </body> </html>
js部分放在了body后面,才運(yùn)行成功
放在head里面,失敗
放在body的前半部分,也失敗,
為什么呢??
2018-08-19
因為js腳本的加載順序,你放在頭部就會先加載js腳本,那時頁面HTML部分還沒加載,自然獲取不了ID,你的程序也就執(zhí)行不了,你需要在你的腳本中加入window.onload()命令,這個命令我還不太熟,你去網(wǎng)上看一看怎么用吧.
2018-10-15
你可以將
?
var?content=document.getElementById('txt');
放到function函數(shù)里,這樣就不用考慮JS位置了