2017-08-08 53 views

回答

0

我已经创建了一个最简单的例子,说明如何做到这一点。 在代码中查看我的意见以了解其工作原理。

$("#input").focus(function() { 
 
    // If you enter the input 
 

 
    $("#test").animate({ // Animate the text to the top 
 
    top: "20px", 
 
    }, 200, function() {}); 
 

 
}).blur(function() { 
 
    // If you left the input 
 

 
    if ($(this).val() == "") { // Only if the input is empty 
 

 
    $("#test").animate({ // Animate the text back into the input 
 
     top: "50px", 
 
    }, 200, function() {}); 
 
    } 
 
});
#box { 
 
    height: 100px; 
 
    width: 100px; 
 
    padding-top: 50px; 
 
    position: relative; 
 
} 
 

 
#test { 
 
    top: 50px; 
 
    left: 5px; 
 
    position: absolute; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="box"> 
 
    <input type="text" id="input"><span id="test">Test</span> 
 
</div>

0

像这样可以不使用JavaScript的纯CSS一行中容易地实现。我在下面添加了一段代码来演示基本思想。我将required attribute用于与:valid css selector组合的输入,以检查输入是否为空。

label { 
 
    display: inline-block; 
 
    margin-top: 20px; 
 
    position: relative; 
 
} 
 

 
label > span { 
 
    position: absolute; 
 
    cursor: text; 
 
    left: 2px; 
 
    top: 1px; 
 
    transition: top .2s ease; 
 
    color: #3a3a3a; 
 
} 
 

 
label > input:focus + span, 
 
label > input:valid + span{ 
 
    top: -20px; 
 
}
<label> 
 
    <input required type="text" /> 
 
    <span>Surname</span> 
 
</label>