javascript設(shè)置元素屬性的方法:首先使用“document.getElementById("id值")”語(yǔ)句獲取元素對(duì)象;然后使用“元素對(duì)象.setAttribute("屬性名稱(chēng)","屬性值")”語(yǔ)句來(lái)添加或修改元素屬性。
本教程操作環(huán)境:windows7系統(tǒng)、javascript1.8.5版、Dell G3電腦。
javascript設(shè)置元素屬性的方法
在javascript中,可以使用setAttribute()方法來(lái)設(shè)置元素屬性
語(yǔ)法:
setAttribute("屬性名稱(chēng)","屬性值")
示例:
<img id="img" src="img/1.jpg" /> <p id="demo">點(diǎn)擊按鈕來(lái)設(shè)置img圖片的 width 屬性。</p> <button onclick="myFunction()">試一下</button> <script> function myFunction() { document.getElementById("img").setAttribute("width", "200"); } </script>
效果圖:
擴(kuò)展資料:
removeAttribute()是用來(lái)刪除標(biāo)簽屬性的,語(yǔ)法:
removeAttribute("屬性名")
getAttribute()可以獲取標(biāo)簽指定屬性的值,語(yǔ)法:
getAttribute("屬性名")
【推薦學(xué)習(xí):javascript高級(jí)教程】