javascript 我可以使用 JQuery 获得突出显示的文本吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17227070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:33:10  来源:igfitidea点击:

Can I get highlighted text with JQuery?

javascriptjqueryhighlight

提问by Mr. Lavalamp

I'm not finding anything anywhere. Is there a JQuery solution to retrieve highlighted text? I need to check the highlighted text for spans, get those spans' style attributes, and manipulate them based on that. I can do that part with regular expressions or whatever obviously, but first I need access to the highlighted text! I'm struggling to even find a cross-browser plain javascript solution, so if you've got one of those handy that would help immensely as well.

我在任何地方都找不到任何东西。是否有 JQuery 解决方案来检索突出显示的文本?我需要检查突出显示的跨度文本,获取这些跨度的样式属性,并基于此操作它们。我可以用正则表达式或其他明显的东西来做那部分,但首先我需要访问突出显示的文本!我什至很难找到一个跨浏览器的纯 javascript 解决方案,所以如果你有一个方便的解决方案,那也会有很大帮助。

Thanks!

谢谢!

回答by yeyene

You mean text selection with mouse, so check here, DEMO http://jsfiddle.net/yeyene/GYuBv/2/

你的意思是用鼠标选择文本,所以在这里检查,DEMO http://jsfiddle.net/yeyene/GYuBv/2/

$('#showSelected').on('click', function(){

    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }

    alert(text);       
});

If you want to do some changes around selected text, check this DEMO http://jsfiddle.net/yeyene/GYuBv/3/

如果您想对选定的文本进行一些更改,请查看此演示http://jsfiddle.net/yeyene/GYuBv/3/