我有一个输入,它有一个占位符。我已经成功地设置了占位符的样式,但是当我尝试将占位符移动到顶部时,当输入聚焦时它不起作用,我使用的是绝对位置,并且顶部位置具有负值。
这是我的代码:
<style>
#wrapper {
padding:40px;
position:relative;
}
input {
display:block;
position : relative;
}
input::-webkit-input-placeholder {
color: red;
position:absolute;
}
input:focus::-webkit-input-placeholder {
top:-20px;
color:blue;
}
</style>
<div id="wrapper">
<input type="text" placeholder="Engkus Kusnadi">
</div>
Run Code Online (Sandbox Code Playgroud)
这是我的小提琴: https: //jsfiddle.net/su2roqvc/2/
我缺少什么?
您可以使用并且它可以在所有labels浏览器中运行!
升级门
添加了 js 以实现更好的行为。
var fields = $('.js-field');
fields.each(function() {
var input = $(this).find('input');
var placeholder = $(this).find('span');
input.on('blur', function() {
$(this).val() == ""
? placeholder.show()
: placeholder.hide();
});
input.on('focus', function() {
placeholder.show()
});
});Run Code Online (Sandbox Code Playgroud)
label {
display: block;
width: 200px;
position: relative;
padding-top: 20px;
margin-top: 20px;
}
input {
height: 30px;
width: 100%;
border: 1px solid black;
padding: 5px;
box-sizing: border-box;
}
span {
position: absolute;
display: block;
top: 20px;
left: 5px;
color: red;
font-family: sans-serif;
font-size: 14px;
line-height: 30px;
transition: .3s ease;
}
input:focus + span {
transform: translateY(-100%);
color: blue;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="js-field">
<input>
<span>Placeholder1</span>
</label>
<label class="js-field">
<input>
<span>Placeholder2</span>
</label>Run Code Online (Sandbox Code Playgroud)