Delay HTML5 :invalid pseudo-class until the first event

前端 未结 13 2091
旧巷少年郎
旧巷少年郎 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:02

    This is a VanillaJS (no jQuery) version of kzh's answer

    {
      let f = function() {
        this.classList.add('touched')
      }
      document
        .querySelectorAll('input')
        .forEach((e) => {
          e.addEventListener('blur', f, false)
          e.addEventListener('keydown', f, false)
        })
    }
    /**
     * All required inputs initially are yellow.
     */
    :required {
      background-color: lightyellow;
    }
    
    /**
     * If a required input has been touched and is valid, it should be white.
     */
    .touched:required:valid {
      background-color: white;
    }
    
    /**
     * If a required input has been touched and is invalid, it should be pink.
     */
    .touched:required:invalid {
      background-color: pink;
    }

提交回复
热议问题