![](/img/trans.png)
[英]How do you set an inline css style to an element using JavaScript?
[英]How to set inline CSS of element to default using javascript?
我有一個簡單的功能,我在選中復選框時更改文本的默認樣式,並在取消選中復選框時將樣式更改回默認值。
terms.style = "";
應該將樣式重置為默認值,但由於某些原因它沒有,我完全不知道為什么。 我知道當復選框被取消選中時會執行else范圍,因為我已經通過手動輸入不同的樣式進行了測試。
const form = document.getElementById('form');
const checkBox = form.querySelector('input[name=termsCheckBox]');
checkBox.addEventListener('click', function(){
const terms = document.getElementById('termsText');
if (checkBox.checked){
terms.style = "color: black; font-weight: normal";
} else {
terms.style = "";
}
});//end of function
您可以使用getAttribute()
在元素的style
屬性中獲取內聯CSS,並將其存儲在變量中,並在選中/取消選中復選框insert並從style
屬性中刪除它
var checkBox = document.querySelector('#form input[name=termsCheckBox]'), terms = document.getElementById('termsText'), style = terms.getAttribute('style'); checkBox.addEventListener('click', function(){ if (checkBox.checked) terms.style.cssText = "color:black; font-weight:normal"; else terms.style.cssText = style; });
<form id="form"> <input type="checkbox" name="termsCheckBox"> <textarea id="termsText" style="color:red; font-weight:bold">termsText</textarea> </form>
據MDN稱 :
不應通過直接為樣式屬性指定字符串來設置樣式(如elt.style =“color:blue;”)
正確的方法是:
checkBox.addEventListener('click', function(){
const terms = document.getElementById('termsText');
if(checkBox.checked){
terms.style.color = "black";
terms.style.fontWeight = "normal";
}else{
terms.style.color = "";
terms.style.fontWeight = "";
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.