简体   繁体   English

使用JS和HTML可以更改样式,但JS和CSS并不总是

[英]Changing style using JS & HTML works, JS & CSS doesn't always

Using JS & HTML markup Always works: Codepen 使用JS和HTML标记始终有效: Codepen

if (document.forms['myForm'].name.value == '') {
    name.style.background = "pink";
}
else {
    name.style.background = "white";
}

Using JS & CSS Doesn't always work: Codepen 使用JS和CSS 并不总是有效: Codepen

if (document.forms['myForm'].name.value == '') {
    // give this element the .error class from the css file
    name.className = name.className + " error";
}
else {
    // this removes the error class
    name.className = name.className.replace(" error", ""); 
}

Why is JS & CSS inconsistent? 为什么JS和CSS不一致? I would like to use this approach since I can just apply an error class to each of the elements I want to effect. 我想使用这种方法,因为我可以将错误类应用于我想要影响的每个元素。

Everytime you hit your submit button and a field isn't filled out, error is added to the classList property; 每次您单击提交按钮时,如果没有填写字段, error添加到classList属性; if you submit more than once, multiple classes will be added. 如果您提交不止一次,则将添加多个课程。 Whereas when removing the class, .replace(' error', '') will only replace the first instance of error it comes across. 删除类时, .replace(' error', '')将仅替换遇到的error的第一个实例。

You can use regex to find all instances of error : 您可以使用regex查找所有 error实例:

name.className = name.className.replace(/ error/g, "");

Codepen 码笔

Sidenote: You can take advantage of classList but its browser support is limited. 旁注:您可以利用classList但其浏览器支持有限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM