Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 取消选择contenteditable元素_Javascript_Jquery_Html - Fatal编程技术网

Javascript 取消选择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

我正在尝试删除contenteditable字段中的选择。我的代码是:

<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。使用相同的字体大小,因为我相信自动选择是表单字段独有的。