Javascript 取消选择contenteditable元素
我正在尝试删除contenteditable字段中的选择。我的代码是:Javascript 取消选择contenteditable元素,javascript,jquery,html,Javascript,Jquery,Html,我正在尝试删除contenteditable字段中的选择。我的代码是: <h1 contenteditable>Text</h1> <input type="text" value="Text" /><br/> <input type="button" onclick="" value='Deselect input'> <input type=&qu
<h1 contenteditable>Text</h1>
<input type="text" value="Text" /><br/>
<input type="button" onclick="" value='Deselect input'>
<input type="button" onclick="$('h1').blur()" value='Deselect h1'>
文本
我通过document.execCommand('selectAll',false,null)自动选择h1
的文本代码>
删除对输入的选择会起作用,但对h1
不起作用。我怎样才能做到这一点
检查
这张照片显示了它对我的作用:
如您所见,我刚刚单击了取消选择h1
,文本仍然处于选中状态。我正在使用Chrome。这里的答案解决了我的问题,但由于某种原因它被删除了。是这样的:
将$('h1').blur()替换为window.getSelection().removeAllRanges();“
修复了它。这里的答案解决了我的问题,但由于某种原因它被删除了。它是这样的:
将$('h1').blur()
替换为window.getSelection().removeAllRanges();“
修复了它。以下是工作代码
$(document).ready(function() {
$('h1').focus();
document.execCommand('selectAll', false, null);
})
$("#deselect").click(function(){
window.getSelection().removeAllRanges();
});
这是工作代码
$(document).ready(function() {
$('h1').focus();
document.execCommand('selectAll', false, null);
})
$("#deselect").click(function(){
window.getSelection().removeAllRanges();
});
我在上找到了,应该是您要找的:
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
工作我发现是这样的,应该是你要找的:
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
工作对我来说很好。您使用哪个浏览器?H1文本不会在您的小提琴中自动选择,但取消选择对我来说也很好。@Yuri是的,自动选择是我在编辑时忘记更新的东西。现在应该自动选择h1。使其具有同等的字体大小,因为我相信自动选择是表单字段独有的。对我来说,它工作得很好。您使用哪个浏览器?H1文本不会在您的小提琴中自动选择,但取消选择对我来说也很好。@Yuri是的,自动选择是我在编辑时忘记更新的东西。现在应该自动选择h1。使用相同的字体大小,因为我相信自动选择是表单字段独有的。