通过JavaScript选择文本

时间:2011-01-25 08:32:06

标签: javascript jquery html dom selection

我想选择Html页面上的文字并将其设置为BOLD,我使用以下代码

<script type="text/javascript" >


function getSelectedText(){ 
    if(window.getSelection){   ;
        return window.getSelection().toString(); 
    } 
    else if(document.getSelection){;
        return document.getSelection(); 
    } 
    else if(document.selection){ ;

        return document.selection.createRange().text; 
    } 
} 
$(document).ready(function(){
 $("*").live("mouseup",
    function() {
        selection = getSelectedText(); 
        alert(selection);
        if(selection.length >= 3) {

            $(this).html($(this).html().replace(selection, "<b>" + selection + "</b>") );

        }       
    }
); 
});

</script>

此代码工作正常但是当文本位于两个不同的段落/ Div或文本之间有链接时,它似乎无法正常工作。

我怎么能让它发挥作用?

4 个答案:

答案 0 :(得分:2)

如果您想对当前选择进行某种突出显示,使用内置document.execCommand()是最简单的方法。它适用于所有主流浏览器。

以下内容应该在任何选择中执行您想要的操作,包括跨越多个元素的选择。在非IE浏览器中,它会打开designMode,应用背景颜色,然后再次关闭designMode

<强>更新

已修复在IE 9中工作。

function makeEditableAndHighlight(colour) {
    var range, sel = window.getSelection();
    if (sel.rangeCount && sel.getRangeAt) {
        range = sel.getRangeAt(0);
    }
    document.designMode = "on";
    if (range) {
        sel.removeAllRanges();
        sel.addRange(range);
    }
    // Use HiliteColor since some browsers apply BackColor to the whole block
    if (!document.execCommand("HiliteColor", false, colour)) {
        document.execCommand("BackColor", false, colour);
    }
    document.designMode = "off";
}

function highlightSelection(colour) {
    var range;
    if (window.getSelection) {
        // IE9 and non-IE
        try {
            if (!document.execCommand("BackColor", false, colour)) {
                makeEditableAndHighlight(colour);
            }
        } catch (ex) {
            makeEditableAndHighlight(colour)
        }
    } else if (document.selection && document.selection.createRange) {
        // IE <= 8 case
        range = document.selection.createRange();
        range.execCommand("BackColor", false, colour);
    }
}

document.onmouseup = function() {
    highlightSelection("red");
};

实例:http://jsfiddle.net/eBqBU/9/

答案 1 :(得分:0)

a=document.getElementById('elementID').innerHTML;

变量'a'将获取元素内的任何内容的字符串值,其id为'elementID'。

这可以吗?

答案 2 :(得分:0)

您需要的所有内容(根据您的评论)都可以在此处找到:http://www.awesomehighlighter.com/webliter.js

我没有时间提取相关部分,但请查看Webliter.prototype.highlight中的示例(只在该文件中搜索此内容)

你也可以使用jQuery例如这个插件:http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html

答案 3 :(得分:0)

如同我今天在类似问题中mentioned一样,有一个jQuery插件。