我有一个 contentEditable 元素,我通过 javascript 添加了一个占位符,但它有 200 毫秒的延迟,这是代码
JavaScript:
function handlePlaceholder () {
var $input = $('.input');
var $placeholder = $('.placeholder');
if ($input.html()) {
$placeholder.hide();
} else {
$placeholder.show();
}
}
$('.input').on('focus blur keyup', function() {
handlePlaceholder();
})
html:
<div class="placeholder">input here</div>
<div class="input" contenteditable="true"></div>
CSS:
.input {
width: 200px;
height: 30px;
line-height: 30px;
font-size: 12px;
margin-top: 30px;
border: 1px solid #999;
position: relative;
z-index: 1;
}
.placeholder {
color: #cdcdcd;
position: absolute;
z-index: 0;
top: 30px;
line-height: 30px;
padding-left: 10px;
}
当keyup事件触发handlePlaceholder函数时,有200ms的延迟,但真正的html占位符没有。
我的问题:是否有另一种方法可以为 contentEditable 元素添加占位符,或者如何以这种方式添加占位符而不造成延迟?
jsfiddle:http://jsfiddle.net/zhouxiaoping/pkgzrb7w/3/
200ms不是确切的时间,只是描述
最佳答案
您可以在零超时时将 keydown
事件与 setTimeout
一起使用,以在默认事件处理程序之后立即触发该函数(因此输入值将在此时更新)
$('.input').on('focus blur keydown', function() {
setTimeout(handlePlaceholder, 0);
})
关于javascript - 可编辑元素占位符不平滑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30164639/