JavaScript操作頁面上的DIV不能用document.form.div來操作,應使用document.all.div操作,且JavaScript不能通過div的name屬性來訪問它,而是訪問div的id屬性來訪問.
工作中,偶爾也會做做前臺,每次都需要對一些簡單的javascript和html標籤進行重新學習,今天就稍微總結一下,主要是針對div的操作,也還包括一些其他基本控件。一.div
document.getElementById("div2").style.display="";//顯示
div2.style.display="";//顯示
關於這四者的區別,網上有段經典的代碼:
<input name="button" value="Button" type="button">
<font color="green">
<h2>This is a DIV!</h2>
</font>
</div>
<input name="innerHTML" value="innerHTML" type="button" OnClick="alert(div.innerHTML);">
<input name="outerHTML" value="outerHTML" type="button" OnClick="alert(div.outerHTML);">
<input name="innerText" value="innerText" type="button" OnClick="alert(div.innerText);">
<input name="outerText" value="outerText" type="button" OnClick="alert(div.outerText);">
innerHTML:在div裏面的html標籤,通過它可以方便的設置div裏要顯示的內容,如:
document.getElementById("div3").innerHTML="<strong>hhh</strong>";
outerHTMl:包括div在內的所有html標籤
innerText:要在div裏顯示的文本,和outerText基本一樣
值得注意的是,以上四個只有innerHTML在firefox下有效,其他均只在IE下可用
<input type="text" id="text1" value="" style="WIDTH:300px" maxlength=40>
style="WIDTH:300px":可以限定輸入框的顯示長度
maxlength=40:可以限制該輸入框允許輸入字符的最大長度
document.getElementById("text1").value="輸入框";
值得注意的是,javascript是從頭到尾編譯的,因此在使用控件之前,一定要確保該控件已經被加載到了頁面中。