如何使用 javascript 将元素的内联 CSS 设置为默认值?

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

根据MDN

Styles should not be set by assigning a string directly to the style property (as in 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 = "";
    }
});

您可以使用 getAttribute() 在元素的 style 属性中获取内联 CSS 并将其存储在变量中,并在复选框的 check/uncheck 上插入并从 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>