该脚本只是将用户值附加到其value属性,因此可以使用CSS设置其样式
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;}<p> <label> <input oninput="this.setAttribute('value', this.value)" type="text" name="your-name" value="" size="40" required> <span>Name</span> </label></p>
由于使用CSS更改HTML5输入的占位符是一个热门话题,因此,这里有一些其他选择,它们具有更简单,更可重用的标记结构
.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;}<div > <input oninput="this.setAttribute('value', this.value)" type="text" name="name" value="" required> <label>Name</label></div>
由于脚本非常小,因此我可以将其内联应用,尽管当然可以使用外部事件处理程序添加相同的行为,例如这样,并针对多个对象
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;}<div > <input type="text" name="name" value="" required> <label>Name</label></div><div > <input type="text" name="email" value="" required> <label>Email</label></div><div > <input type="text" name="address" value=""> <label>Address</label></div>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)