Javascript从页面上的任何textinput / textarea获取选定的文本 [英] Javascript get selected text from any textinput/textarea on the page

查看:74
本文介绍了Javascript从页面上的任何textinput / textarea获取选定的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我不知道哪一个是活动的(聚焦的),如何从文本框/文本区域中获取所选文本。我正在尝试创建一个小书签,用于更正页面上任何类型输入中的选定文本。

How can get the selected text from a textbox/textarea if I don't know which one active (focused). I am trying to create a small bookmarklet that will correct the selected text in any type of input on a page.

推荐答案

选择,你想 selectionStart selectionEnd

As对于当前关注的元素,使用 document.activeElement

As for the currently focused element, use document.activeElement.

因此,您可以使用组合: http://jsfiddle.net/rBPte/1/

So as a combination you can use: http://jsfiddle.net/rBPte/1/.

正如Tim Down指出的那样,对于Internet Explorer 8或更低版本,您需要一个更复杂的解决方案:在textarea中的插入位置,从一开始就是字符

As Tim Down pointed out, you'd need a more complex solution for Internet Explorer version 8 or lower: Caret position in textarea, in characters from the start

function getText(elem) { // only allow input[type=text]/textarea
    if(elem.tagName === "TEXTAREA" ||
       (elem.tagName === "INPUT" && elem.type === "text")) {
        return elem.value.substring(elem.selectionStart,
                                    elem.selectionEnd);
        // or return the return value of Tim Down's selection code here
    }
    return null;
}

setInterval(function() {
    var txt = getText(document.activeElement);
    document.getElementById('div').innerHTML =
        txt === null ? 'no input selected' : txt;
}, 100);

这篇关于Javascript从页面上的任何textinput / textarea获取选定的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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