Delay HTML5 :invalid pseudo-class until the first event

前端 未结 13 2079
旧巷少年郎
旧巷少年郎 2020-11-30 04:35

I recently discovered that the :invalid pseudo-class applies to required form elements as soon as the page loads. For example, if you have this cod

13条回答
  •  無奈伤痛
    2020-11-30 05:01

    A good way is to abstract :invalid, :valid with a CSS classes and then some JavaScript to check if the input field was focused or not.

    CSS:

    input.dirty:invalid{ color: red; }
    input.dirty:valid{ color: green; }
    

    JS:

    // Function to add class to target element
    function makeDirty(e){
      e.target.classList.toggle('dirty');
    }
    
    // get form inputs
    var inputs = document.forms[0].elements;
    
    // bind events to all inputs
    for(let input of inputs){
      input.addEventListener('invalid', makeDirty);
      input.addEventListener('blur', makeDirty);
      input.addEventListener('valid', makeDirty);
    }
    

    DEMO

提交回复
热议问题