方法:1、使用“element.innerText='值'”或“element.innerHTML='值'”語句修改元素內(nèi)容;2、使用“element.style”或“element.className”語句修改元素樣式屬性。
本教程操作環(huán)境:windows7系統(tǒng)、javascript1.8.5版、Dell G3電腦。
操作修改元素
JavaScript的DOM操作可以改變網(wǎng)頁內(nèi)容、結(jié)構(gòu)和樣式,我們可以利用DOM操作元素來改變元素里面的內(nèi)容、屬性等。
改變元素的內(nèi)容
element.innerText
從起始位置到終止位置的內(nèi)容,但它去除html標(biāo)簽,同時空格和換行也會去掉
element.innerHTML
起始位置到終止位置的全部內(nèi)容,包括html標(biāo)簽,同時保留空格和換行。
innerText不識別HTML標(biāo)簽,innerHTML識別HTML標(biāo)簽。這兩個屬性是可讀寫的。
<body> <button> 顯示系統(tǒng)當(dāng)前時間 </button> <div> 某個時間 </div> <script> var btn = document.querySelector('button'); var div = document.querySelector('div'); btn.onclick = function(){ div.innerText = getDate(); } function getDate(){ var date = new Date(); var year = date.getFullYear(); var month = date.getMonth()+1; var dates = date.getDate(); var arr = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六']; var day = date.getDay(); return '今天是'+year+'年'+month+'月'+dates+'日'+arr[day]; } </script> </body>
運行后,顯示某個時間,當(dāng)點擊顯示系統(tǒng)當(dāng)前時間即可顯示進當(dāng)前的日期及星期。
修改樣式屬性
element.style修改行內(nèi)式操作,element.className修改類名樣式屬性
<head> <style> div { width:200px; height:200px; background-color:pink; } </style> </head> <body> <div> </div> <script> var div = document.quertSelector('div'); div.onclick = function(){ this.style.backgroundColor = 'purple'; this.style.width='300px'; } </script> </body>
程序運行后,出現(xiàn)一個寬高均為200像素的粉紅色盒子,點擊盒子,變成寬300像素高200像素的紫色盒子。JS修改style樣式操作,產(chǎn)生的是行內(nèi)樣式。
使用className更改樣式屬性
<head> <style> div { width:100px; height:100px; background-color:pink; } .change { width:200px; height:200px; background-color:purple; } </style> </head> <body> <div> 文本 </div> <script> vet test =document.querySelector('div'); test.onclick = function(){ //將當(dāng)前元素的類名改為change this.className = 'change'; } </script> </body>
【