【发布时间】:2013-11-15 00:10:06
【问题描述】:
我正在创建一个 jQuery 占位符,该占位符的作用类似于不支持的浏览器的 chrome/firefox 默认占位符,但我无法让占位符 div 的 html 的更改速度与 chrome/firefox 的默认占位符更改的速度一样快。它仅在我松开按键或按下按键时才会发生变化,仅当输入中至少有 2 个字符时才会发生变化。我该如何解决这个问题?
<html>
<head>
<title>Place Holder</title>
<style media="screen" type="text/css">
input{
position:absolute;
top:4px;
left:4px;
background:transparent;
}
#default{
top:30px;
}
#ph{
color:LightGray;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
window.onload = function() {
$("#txt")
.keypress(function(){
if($('#txt').val().length > 0){
$('#ph').html('');
} else {
$('#ph').html('Custom Place Holder');
}
})
.keyup(function() {
if($('#txt').val().length > 0){
$('#ph').html('');
} else {
$('#ph').html('Custom Place Holder');
}
});
}
</script>
</head>
<body>
<div id="ph">Custom Place Holder</div>
<input id="txt" type="text" />
<input id="default" type="text" placeholder="Default Placeholder"/>
</body>
</html>
【问题讨论】:
-
我使用定时器(setTimeout)解决了这个问题,但我不知道在这种情况下使用定时器是否是个好习惯。 jsfiddle.net/HW7tK/10
标签: javascript jquery html placeholder