getSelection中没有alt属性和脚本

getSelection without alt attribute and scripts in it?

本文关键字:属性 脚本 alt getSelection      更新时间:2023-09-26

我使用的是window。getSelection()获取所选文本。但是,如果我也选择了一个图像,它也会返回一个图像。

的例子:

<img src="someSrc.jpg" alt="image_alt" /> My text here ... 

如果我也选择一个图像,它返回

我的文字在这里

但我只需要

My text here .

有没有办法只得到文本,没有alt?

谢谢

试试这个:

window.getTextSelection = function() {
    //First get HTML Fragment of selection
    var html = window.getSelection().getRangeAt(0).cloneContents(); 
    //Return only the text
    return html.textContent||html.innerText;
}

在某些情况下,你可以简单地通过CSS禁用用户选择:希望您也可以通过禁用图像的用户选择来实现这一点:

img {
        -webkit-user-select: none;
        -khtml-user-select: none;
        -moz-user-select: none;
        -o-user-select: none;
        user-select: none;
}

最简单的方法是使用toString()方法来选择范围(s),这是在WHATWG的新范围规范的当前版本中指定window.getSelection().toString()要做的(尽管这与某些浏览器所做的相反,可能会或可能不会改变)。下面的代码将适用于多个选择范围(Mozilla支持),也适用于IE <9 .

jsFiddle: http://jsfiddle.net/timdown/HkP2S/

代码:

function getSelectionRangeText() {
    var selText = "";
    if (window.getSelection) {
        var sel = window.getSelection(), rangeCount = sel.rangeCount;
        if (rangeCount) {
            for (var i = 0, rangeTexts = []; i < rangeCount; ++i) {
                rangeTexts.push("" + sel.getRangeAt(i));
            }
            selText = rangeTexts.join("");
        }
    } else if (document.selection && document.selection.type == "Text") {
        selText = document.selection.createRange().text;
    }
    return selText;
}

此解决方案包括<script><style>元素内的文本。为了消除这种情况,可以在选择范围上使用cloneContents()并遍历结果文档片段的DOM,仅从不包含在<script><style>元素中的文本节点收集文本。您还可以在此基础上扩展以删除CSS display: none元素内的文本。

jsFiddle: http://jsfiddle.net/timdown/HkP2S/2/

代码:

function getSelectionRangeText() {
    var selText = "", selTextParts = [];
    function getNodeText(node) {
        if (node.nodeType == 3) {
            selTextParts.push(node.data);
        } else if (node.hasChildNodes()
        && !(node.nodeType == 1 && /^(script|style)$/i.test(node.tagName))) {
            for (var child = node.firstChild; !!child; child = child.nextSibling) {
                getNodeText(child);
            }
        }
    }
    if (window.getSelection) {
        var sel = window.getSelection(), rangeCount = sel.rangeCount;
        if (rangeCount) {
            for (var i = 0; i < rangeCount; ++i) {
                getNodeText(sel.getRangeAt(i).cloneContents());
            }
            selText = selTextParts.join("");
        }
    } else if (document.selection && document.selection.type == "Text") {
        selText = document.selection.createRange().text;
    }
    return selText;
}