专注时更改div的CSS

时间:2018-12-12 18:03:26

标签: javascript

我在输入焦点时更改div的css。但是我想在输入中输入字母时取消焦点的值。

那么当我在输入中输入值时如何呈现div的初始CSS?

为方便起见,我创建了一个代码段。

function setFocused() {
      var results = document.querySelectorAll('.test');
      for (result of results) {
        result.classList.add('focused');
      }
    }

    function unsetFocused() {
      var results = document.querySelectorAll('.test');
      for (result of results) {
        result.classList.remove('focused');
      }
    }

    var results = document.querySelectorAll('input[type="text"]');
    for (result of results) {
      result.addEventListener("focus", setFocused);
      result.addEventListener("blur", unsetFocused);
    }
.test.focused {
      color: red;
    }
<form>
    <input type="text"/>
</form>
    <div class="test">
        Hello
    </div>

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您可以为输入(键入)添加一个eventListener。在该功能上,您可以删除类。

我希望这可以解决问题。请找到以下代码。

function setFocused() {
      var results = document.querySelectorAll('.test');
      for (result of results) {
        result.classList.add('focused');
      }
    }

    function unsetFocused() {
      var results = document.querySelectorAll('.test');
      for (result of results) {
        result.classList.remove('focused');
      }
    }
    
    function onChange(){
            var results = document.querySelectorAll('.test');
              result.classList.remove('test','focused');

    }

    var results = document.querySelectorAll('input[type="text"]');
    for (result of results) {
      result.addEventListener("focus", setFocused);
      result.addEventListener("blur", unsetFocused);
      result.addEventListener("input", onChange);
    }
.test.focused {
      color: red;
    }
<form>
    <input type="text"/>
</form>
    <div class="test">
        Hello
    </div>