带有占位符的可编辑 div 中的光标未出现在 Google Chrome 中的正确位置
The cursor in an editable div with a placeholder does not appears at the good place in Google Chrome
我有一个按钮可以清除带有占位符的简单 editable div
。
如果我在按下按钮之前在可编辑的 div 中输入两行(按回车换行),占位符将出现,但光标将放置在可编辑的 div 旁边,在 Google Chrome.
我用Safari和Firefox测试过,没问题,光标放在可编辑的div。
这段代码有什么问题? (Jsfiddle link)
HTML:
<div class="textarea" contenteditable="true" placeholder="demo"></div>
<button type="button">press me</button>
CSS:
[contenteditable=true]:empty:before{
content: attr(placeholder);
display: block;
}
.textarea{
border-style: solid;
width: 100px;
outline-width: 0;
cursor: text
}
Javascript:
$('button').click(function(){
$('.textarea').empty();
$('.textarea').focus();
});
好的,这似乎解决了我的问题,尽管这个修复有点老套。如果您将 text
设置为 blank space
那么它会解决问题。
我希望其他人可能有一个不那么骇人听闻的修复程序。
$('button').click(function(e){
$('.textarea').text(' ');
$('.textarea').focus();
console.log($('.textarea')[0].innerText.length);
});
编辑
如果您想保留占位符,则创建范围并设置选择似乎可以解决问题。
相关代码如下:
$('button').click(function(e){
$('.textarea').text('');
var range = document.createRange();
var sel = window.getSelection();
range.setStart($('.textarea')[0], 0);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
});
我有一个按钮可以清除带有占位符的简单 editable div
。
如果我在按下按钮之前在可编辑的 div 中输入两行(按回车换行),占位符将出现,但光标将放置在可编辑的 div 旁边,在 Google Chrome.
我用Safari和Firefox测试过,没问题,光标放在可编辑的div。
这段代码有什么问题? (Jsfiddle link)
HTML:
<div class="textarea" contenteditable="true" placeholder="demo"></div>
<button type="button">press me</button>
CSS:
[contenteditable=true]:empty:before{
content: attr(placeholder);
display: block;
}
.textarea{
border-style: solid;
width: 100px;
outline-width: 0;
cursor: text
}
Javascript:
$('button').click(function(){
$('.textarea').empty();
$('.textarea').focus();
});
好的,这似乎解决了我的问题,尽管这个修复有点老套。如果您将 text
设置为 blank space
那么它会解决问题。
我希望其他人可能有一个不那么骇人听闻的修复程序。
$('button').click(function(e){
$('.textarea').text(' ');
$('.textarea').focus();
console.log($('.textarea')[0].innerText.length);
});
编辑
如果您想保留占位符,则创建范围并设置选择似乎可以解决问题。
相关代码如下:
$('button').click(function(e){
$('.textarea').text('');
var range = document.createRange();
var sel = window.getSelection();
range.setStart($('.textarea')[0], 0);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
});