【问题标题】:Clear a selection in Firefox清除 Firefox 中的选择
【发布时间】:2011-09-05 10:08:32
【问题描述】:

我有这个功能

function smth() {
var container = null;
var newContainer = null;
if (window.getSelection) {  // all browsers, except IE before version 9
    alert("first if");
    var selectionRange = window.getSelection();
    if (selectionRange.rangeCount > 0) {
        var range = selectionRange.getRangeAt(0);
        container = range.commonAncestorContainer;
        newContainer = container;
    }
}
else {
    if (document.selection) {   // Internet Explorer
        alert("second if");
        var textRange = document.selection.createRange();
        container = textRange.parentElement();
    }
}

if (newContainer) {
    return newContainer.nodeName;
}
else {
    alert("Container object for the selection is not available!");
}
}     

现在,在我完成我需要对选择执行的操作后,我需要清除它。我尝试了一些没有用的东西,有什么想法吗?

document.selection.clear ()    

这没用。

【问题讨论】:

    标签: javascript range selection


    【解决方案1】:

    对于有问题的浏览器:

    document.selection.empty()
    

    对于其他浏览器:

    window.getSelection().removeAllRanges()
    

    http://help.dottoro.com/ljigixkc.php

    【讨论】:

    • 不会按预期工作,例如在 tinymce 编辑器窗口(实际上是 iframe)中。您将需要使用:tinymce.activeEditor.selection.collapse();
    • “对于有问题的浏览器”不再是这种情况。此处的后一个选项适用于所有浏览器,包括最新版本的 IE。 (假设您通过“有问题”指的是 IE。)
    【解决方案2】:

    注意:如果您选择的是 input 或 textarea 元素的文本,那么如果您使用 input 或 textarea 的标准原生 html 元素选择方法,您的代码将获得更多跨浏览器支持。

    如果使用本机选择方法选择了 html 输入或 textarea 元素,则使用上面建议的方法在我的 firefox 44.0.2 上不起作用。对它有用的,我想适用于所有浏览器的,是运行以下代码,它创建一个新元素并选择它。新元素不能与display:nonevisibility:hidden 一起使用,因为在我的Firebox 中没有选择它,所以诀窍是通过将所有大小属性​​强制为0\none 使其不可见。

    var tempElement = document.createElement("input");
    tempElement.style.cssText = "width:0!important;padding:0!important;border:0!important;margin:0!important;outline:none!important;boxShadow:none!important;";
    document.body.appendChild(tempElement);
    tempElement.select();
    /* Use removeChild instead of remove because remove is less supported */
    document.body.removeChild(tempElement);
    

    【讨论】:

    • @LawrenceDol 如果失去焦点对你来说是个问题,那么你可以在运行后重新聚焦输入字段。
    【解决方案3】:

    使用 tinymce.activeEditor.selection.collapse() 如果那不起作用,那么使用 const range = tinymce.activeEditor.dom.createRng(); tinymce.activeEditor.selection.setRng(range)

    【讨论】:

      猜你喜欢
      • 2019-02-15
      • 1970-01-01
      • 2014-07-28
      • 1970-01-01
      • 2014-05-29
      • 1970-01-01
      • 2019-04-06
      • 2012-07-03
      • 1970-01-01
      相关资源
      最近更新 更多