css attr的使用

2017-03-18  本文已影响0人  yongningfu

经常有需要是,在用户输入错误的时候给用户进行提示,一般我们可能会在input的下面隐藏一个span,来进行提示,如果用dom操作它的text,这样做算是比较麻烦的,操作的对象多,有没有更加简单的方法呢?

css 的attr给出了这种可能,attr可以获取某个元素的属性值

<!DOCTYPE html>
<html>
  <head>
      <meta charset="utf-8" />
      <style type="text/css">

        #inputBox {
          position: relative;
        }
        #inputBox::after {
          content: attr(tips);
          position: absolute;
          background: orange;
          left: 0px;
          top: 1.5em;
        }
                
      </style>
  </head>
  <body>
    <!-- 目前 input 不支持before after -->
    <div id="inputBox" tips="">
      <input type="text" id="inputLine"/>
    </div>

    <script type="text/javascript">
      //输入错误的时候 进行提示
      document.getElementById("inputLine").onblur = function(event) {
        var target = event.target || event.srcElement;
        var value= target.value;
        var reg = /\w+@\w+\.\w{2,3}/;
        if (!reg.test(value)) {
          document.getElementById("inputBox").setAttribute("tips", "邮箱验证错误");
        }
      }
      
    </script>
  </body>
</html>
Paste_Image.png

上面的做法还不是最好的,因为不能加边框,如果加边框的话,会有即使 tips没有内容的话,还是会有边框显示出来

有没有更好一点的呢? 当然是使用css的边框选择器了

<!DOCTYPE html>
<html>
  <head>
      <meta charset="utf-8" />
      <style type="text/css">
        /*存在tips属性的时候 inputBox才...*/
        #inputBox[tips] {
          position: relative;
        }
        #inputBox[tips]::after {
          content: attr(tips);
          position: absolute;
          border: 1px solid gray;
          background: orange;
          left: 0px;
          top: 1.5em;
        }
                
      </style>
  </head>
  <body>
    <!-- 目前 input 不支持before after -->
    <div id="inputBox">
      <input type="text" id="inputLine"/>
    </div>
    <div>aaaaa</div>

    <script type="text/javascript">
      //输入错误的时候 进行提示
      document.getElementById("inputLine").onblur = function(event) {
        var target = event.target || event.srcElement;
        var value= target.value;
        var reg = /\w+@\w+\.\w{2,3}/;
        if (!reg.test(value)) {
          document.getElementById("inputBox").setAttribute("tips", "邮箱验证错误");
        }
      }

      document.getElementById("inputLine").onfocus = function(event) {
        document.getElementById("inputBox").removeAttribute("tips");
      }
      
    </script>
  </body>
</html>

通过对比发现,只有在有对应属性的情况下,after才进行对应的显示。 所以一开始它是没有border的

Paste_Image.png
上一篇 下一篇

猜你喜欢

热点阅读