简体   繁体   English

如果文本字段为空,则使用JavaScript应用CSS样式

[英]Applying a CSS style using JavaScript if text field is empty

I have this function in JavaScript which I called using an onclick event in my HTML code: 我在JavaScript中有此函数,我在HTML代码中使用onclick事件调用了此函数:

function checkTextField(field) {
if (field.value == '') {
    sheet.insertRule("input:focus {background: #fc9fff;}", 1);
  }
}

I've checked that the if statement works by using an alert statement within it instead of the insertrule, but it seems that the css is applied even though the value of the field is not empty. 我已经检查了if语句是否可以通过在其中使用警报语句而不是insertrule来工作,但是即使该字段的值不为空,似乎仍应用了CSS。 Is there anything else I can use? 还有什么我可以用的吗?

The problem is when the check method is executed with an empty element, you are inserting a general rule for input:focus which is not removed when focus from the current element is removed. 问题是当用空元素执行check方法时,您正在为input:focus插入一条通用规则,当移除当前元素的焦点时,该规则不会被移除。

A better option would be to use a class like 更好的选择是使用类似

function checkTextField(field) {
    if (field.value == '') {
        field.classList.add('empty')
    } else {
        field.classList.remove('empty')
    }
}

then in your stylesheet 然后在您的样式表中

input.empty:focus {
    background: #fc9fff;
}

也许更好的方法是将您的功能附加到这样的onchange事件上

<input type="text" onchange="checkTextField" />

I'm not sure if I fully understand your question but I've created test HTML file and that test works: 我不确定我是否完全理解您的问题,但是我已经创建了测试HTML文件,并且该测试有效:

<html>
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <style></style>
    <script>
var styleAlreadyAppended = false;
function checkTextField(field) {
    var sheet = document.styleSheets[0];
    if (field.value == '' && styleAlreadyAppended !== true) {
        sheet.insertRule("input:focus {background: #f30;}", 0);
        styleAlreadyAppended = true;
    }
    else if (field.value != '' && styleAlreadyAppended === true) {
        sheet.deleteRule(0);
    }
}
    </script>
</head>
<body>
    <div>
        <input id="testinput" type="text" value="">
        <button onclick="checkTextField(document.getElementById('testinput'))">test</button>
    </div>
</body>
</html>

Tested on FF36. 在FF36上测试。

You can go pure CSS using the :required and :invalid selector and setting the required attribute on the field. 您可以使用:required:invalid选择器并在字段上设置required属性来使用纯CSS。

<style>
   input:required:invalid { background: #fc9fff; }      
</style>

<input name="email" required />

Live version here: http://jsfiddle.net/devotis/z319pp1f/ 此处的实时版本: http//jsfiddle.net/devotis/z319pp1f/

I admit it's a bit hostile to start all required fields red. 我承认将所有必填字段都以红色开头有点敌意。

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

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