<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> .box{ width:200px; height:30px; border:1px solid #aaa; position: relative; border-radius: 5px; } input{ height:30px; width:100%; border-radius: 5px; } span{ position:absolute; top:10px; left:10px; background: pink; transition: all 0.5s ease-in; background: pink; } </style> </head> <body> <div class="box"> <span>姓名:</span> <input type="text"> </div> </body> <script src="js/jquery-1.4.2.min.js"></script> <script> $(function(){ $('input').focus(function(){ $('span').css('top','-10px'); }); $('input').blur(function(){
if($('input').val()=="){
$('span').css('top','10px');
}
else{
$('span').css('top','-10px');
}
})
})
//原生
<script>
window.onload = function(){
var oInput = document.querySelector('input');
var oSpan = document.querySelector('span');
oInput.onfocus = function(){
oSpan.style.top = -10 + 'px';
};
oInput.onblur = function(){
if(oInput.value == ""){
console.log('我的内容为空');
oSpan.style.top = 10 + 'px';
}else{
oSpan.style.top = -10 + 'px';
};
};
}
</script>
</script> </html>