[英]How to set inline CSS of element to default using javascript?
I have simple function in which I change the default styling of text when a checkbox is checked, and change the styling back to default when checkbox gets unchecked. 我有一个简单的功能,我在选中复选框时更改文本的默认样式,并在取消选中复选框时将样式更改回默认值。
The terms.style = "";
terms.style = "";
should reset the style back to default, but for some reasons it doesn't, and I have absolutely no idea why. 应该将样式重置为默认值,但由于某些原因它没有,我完全不知道为什么。 I know that the else scope is performed when checkbox gets unchecked, as I have tested it with manually entering different 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
You can get inline CSS in style
attribute of element using getAttribute()
and store it in variable and on check/uncheck of checkbox insert and remove it from style
attribute 您可以使用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>
Styles should not be set by assigning a string directly to the style property (as in elt.style = "color: blue;") 不应通过直接为样式属性指定字符串来设置样式(如elt.style =“color:blue;”)
Correct way would be: 正确的方法是:
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.