方法:1、使用“element.innerText='值'”或“element.innerHTML='值'”語(yǔ)句修改元素內(nèi)容;2、使用“element.style”或“element.className”語(yǔ)句修改元素樣式屬性。
本教程操作環(huán)境:windows7系統(tǒng)、javascript1.8.5版、Dell G3電腦。
操作修改元素
JavaScript的DOM操作可以改變網(wǎng)頁(yè)內(nèi)容、結(jié)構(gòu)和樣式,我們可以利用DOM操作元素來(lái)改變?cè)乩锩娴膬?nèi)容、屬性等。
改變?cè)氐膬?nèi)容
element.innerText
從起始位置到終止位置的內(nèi)容,但它去除html標(biāo)簽,同時(shí)空格和換行也會(huì)去掉
element.innerHTML
起始位置到終止位置的全部?jī)?nèi)容,包括html標(biāo)簽,同時(shí)保留空格和換行。
innerText不識(shí)別HTML標(biāo)簽,innerHTML識(shí)別HTML標(biāo)簽。這兩個(gè)屬性是可讀寫(xiě)的。
<body> <button> 顯示系統(tǒng)當(dāng)前時(shí)間 </button> <div> 某個(gè)時(shí)間 </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>
運(yùn)行后,顯示某個(gè)時(shí)間,當(dāng)點(diǎn)擊顯示系統(tǒng)當(dāng)前時(shí)間即可顯示進(jìn)當(dāng)前的日期及星期。
修改樣式屬性
element.style修改行內(nèi)式操作,element.className修改類(lèi)名樣式屬性
<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>
程序運(yùn)行后,出現(xiàn)一個(gè)寬高均為200像素的粉紅色盒子,點(diǎn)擊盒子,變成寬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)前元素的類(lèi)名改為change this.className = 'change'; } </script> </body>
【