Simulation of a placeholder

后端 未结 2 1688
梦毁少年i
梦毁少年i 2020-11-30 14:34

I have a Wordpress plugin which I don\'t want to touch, so I\'m hoping my goal can be achieved with CSS only. I have fiddled (no pun intended) with the CSS in Chrome Develop

2条回答
  •  粉色の甜心
    2020-11-30 15:08

    With a small markup change and a script you can do this

    The script simply append the user value to its value attribute, so one can use CSS to style it

    p label {
      position: relative;
    }
    p label input {
      margin-top: 10px;
    }
    p label input[required] + span::after {
      content:  ' *';
      color: red;
    }
    p label span {
      position: absolute;
      top: 2px;
      left: 5px;
      pointer-events: none;
      transition: top .5s;
    }
    p label input:not([value=""]) + span,
    p label input:focus + span {
      top: -20px;
    }


    Since changing a HTML5 input's placeholder with CSS is a hot topic, here is a few more alternatives, with a simpler, more reusable markup structure

    .placeholder {
      position: relative; padding-top: 15px;
    }
    .placeholder label {
      position: absolute; top: 17px; left: 5px;
      pointer-events: none; transition: top .5s;
    }
    .placeholder input[required] + label::after {
      content:  ' *'; color: red;
    }
    .placeholder input:not([value=""]) + label,
    .placeholder input:focus + label {
      top: -5px;
    }


    Since the script is very small, I applied it inline, though one can of course add the same behavior with an external event handler, like this, and target more than one input.

    window.addEventListener('load', function() {
      var placeholders = document.querySelectorAll('.placeholder input');
      for (var i = 0; i < placeholders.length; i++) {
        placeholders[i].addEventListener('input', function() {
          this.setAttribute('value', this.value);
        })
      }
    })
    .placeholder {
      position: relative; padding-top: 15px;
    }
    .placeholder + .placeholder {
      margin-top: 10px;
    }
    .placeholder label {
      position: absolute; top: 17px; left: 5px;
      pointer-events: none; transition: top .5s;
    }
    .placeholder input[required] + label::after {
      content:  ' *'; color: red;
    }
    .placeholder input:not([value=""]) + label,
    .placeholder input:focus + label {
      top: -5px;
    }

提交回复
热议问题