将突出显示的文本存储在变量中 [英] Storing Highlighted text in a variable

查看:52
本文介绍了将突出显示的文本存储在变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个javascript函数可以捕获当前用光标突出显示的文本并将其存储在变量中?我一直在尝试使用document.selection.createRange()。text,但这并没有奏效。有没有可能的选择?这是代码:

Is there a javascript function that will allow me to capture the text that is currently highlighted with the cursor and store it in a variable? I've been trying document.selection.createRange().text but this hasn't been working. Are there any possible alternatives? Here's the code:

function moremagic(){
var output = document.selection.createRange();
alert("I Work!");}

当我运行该功能时,它没有写到写声明,所以我知道出了什么问题。

When I run the function, it doesn't make it to the write statement so I know something is wrong.

推荐答案

无意中被盗另一个问题:

function getSelectedText() {
    if (window.getSelection) {
        return window.getSelection();
    }
    else if (document.selection) {
        return document.selection.createRange().text;
    }
    return '';
}

在onClick函数或其他任何内容中使用此选项,它将返回所选几乎所有浏览器中都有文字。

Use this in a "onClick" function or whatever and it will return the selected text in almost any browser.

这篇关于将突出显示的文本存储在变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆