草庐IT

javascript - 获取当前选中的文本

coder 2024-05-05 原文

我尝试使用 window.getSelection() 在输入中获取当前选定的文本但我总是得到一个空字符串:

expect(browser.executeScript("return window.getSelection().toString();")).toEqual("test");

结果为:

Expected '' to equal 'test'.

使用 angularjs.org 作为目标站点的完整可重现测试:

describe("My test", function () {
    beforeEach(function () {
        browser.get("https://angularjs.org/");
    });

    it("should select text in an input", function () {
        var query = element(by.css("input.search-query"));
        query.sendKeys("test");
        query.sendKeys(protractor.Key.chord(protractor.Key.COMMAND, "a"));

        expect(browser.executeScript("return window.getSelection().toString();")).toEqual("test");
    });
});

请注意,我实际上看到使用 COMMAND +“a”选择了输入的文本。

我做错了什么?

使用 Protractor 2.5.1,firefox 41。

最佳答案

getSelection不适用于在 input 中选择的文本元素,但用于在整个页面上对元素进行的选择。

你可以使用 selectionStartselectionEnd像这样:

return document.activeElement.value.substring(
   document.activeElement.selectionStart,
   document.activeElement.selectionEnd)

您可能应该为此创建一个函数,而不是这个单行代码。也许你还想测试是否 document.activeElement确实是正确的元素类型,等等。当你使用它时,你甚至可以让它与 IE9 之前的浏览器兼容......(difficult though)

简单的功能

这也适用于 inputtextarea没有焦点的控件:

function getInputSelection(el) {
    if (el.selectionStart !== undefined) {
        return el.value.substring(el.selectionStart, el.selectionEnd);
    }
}
// Example call:
console.log(getInputSelection(document.activeElement));

广泛的 jQuery 插件

这提供了更多的跨浏览器兼容性(IE9 之前),并且不仅支持获取,还支持设置选择范围和文本,形式为 jQuery。插入。它处理的事实是 CRLF字符序列以一种实用的方式计为一个字符位置(仅用 LF 就地替换):

/**
 * jQuery plug-in for getting/setting the selection range and text  
 *   within input/textarea element(s). When the selection is set,
 *   the element will receive focus. When getting the selection,
 *   some browsers require the element to have focus (IE8 and below).
 *   It is up to the caller to set the focus first, if so needed.
 * @this {jQuery} Input/textarea element(s).
 * @param {object} opt_bounds When provided, it sets the range as follows:
 * @param {number} opt_bounds.start Optional start of the range. If not
 *   provided, the start point of the range is not altered.
 * @param {number} opt_bounds.end Optional end of the range. If not
 *   provided, the end point of the range is not altered. If null, the end
 *   of the text value is assumed.
 * @param {number} opt_bounds.text Optional text to put in the range. If
 *   not provided, no change will be made to the range's text.
 * @return {jQuery|object|undefined} When setting: the same as @this to 
 *   allow chaining, when getting, an object {start, end, text, length} 
 *   representing the selection in the first element if that info
 *   is available, undefined otherwise.
 */
$.fn.selection = function (opt_bounds) {
    var bounds, inputRange, input, docRange, value;

    function removeCR(s) {
        // CRLF counts as one unit in text box, so replace with 1 char 
        // for correct offsetting
        return s.replace(/\r\n/g, '\n');
    }

    if (opt_bounds === undefined) {
        // Get 
        if (!this.length) {
            return;
        }
        bounds = {};
        input = this[0];
        if (input.setSelectionRange) {
            // Modern browsers
            bounds.start = input.selectionStart;
            bounds.end = input.selectionEnd;
        } else {
            // Check browser support
            if (!document.selection || !document.selection.createRange) {
                return;
            }
            // IE8 or older
            docRange = document.selection.createRange();
            // Selection must be confined to input only
            if (!docRange || docRange.parentElement() !== input) { return; }
            // Create another range that can only extend within the
            // input boundaries.
            inputRange = input.createTextRange();
            inputRange.moveToBookmark(docRange.getBookmark());
            // Measure how many characters we can go back within the input:
            bounds.start =
                -inputRange.moveStart('character', -input.value.length);
            bounds.end = -inputRange.moveEnd('character', -input.value.length);
        }
        // Add properties:
        bounds.length = bounds.end - bounds.start;
        bounds.text = removeCR(input.value).
            substr(bounds.start, bounds.length);
        return bounds;
    }
    // Set
    if (opt_bounds.text !== undefined) {
        opt_bounds.text = removeCR(opt_bounds.text);
    }
    return this.each(function () {
        bounds = $.extend($(this).selection(), opt_bounds);
        bounds.end = bounds.end === null ? this.value.length : bounds.end;
        if (opt_bounds.text !== undefined) {
            value = removeCR(this.value);
            this.value = value.substr(0, bounds.start) + bounds.text +
                value.substr(bounds.end);
            bounds.end = bounds.start + bounds.text.length;
        }
        if (this.setSelectionRange) {
            // Modern browsers
            // Call .focus() to align with IE8 behaviour.
            // You can leave that out if you don't care about that.
            this.focus();
            this.setSelectionRange(bounds.start, bounds.end);
        } else if (this.createTextRange) {
            // IE8 and before
            inputRange = this.createTextRange();
            inputRange.collapse(true);
            inputRange.moveEnd('character', bounds.end);
            inputRange.moveStart('character', bounds.start);
            // .select() will also focus the element:
            inputRange.select();
        }
    });
};

使用示例:

// Get
console.log($('textarea').selection().text);
// Set text
$('textarea').selection({text: "Hello!"});
// Set starting point of selection
$('textarea').selection({start: 1});

关于javascript - 获取当前选中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33483800/

有关javascript - 获取当前选中的文本的更多相关文章

  1. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  2. ruby - 简单获取法拉第超时 - 2

    有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url

  3. ruby - 从 Ruby 中的主机名获取 IP 地址 - 2

    我有一个存储主机名的Ruby数组server_names。如果我打印出来,它看起来像这样:["hostname.abc.com","hostname2.abc.com","hostname3.abc.com"]相当标准。我想要做的是获取这些服务器的IP(可能将它们存储在另一个变量中)。看起来IPSocket类可以做到这一点,但我不确定如何使用IPSocket类遍历它。如果它只是尝试像这样打印出IP:server_names.eachdo|name|IPSocket::getaddress(name)pnameend它提示我没有提供服务器名称。这是语法问题还是我没有正确使用类?输出:ge

  4. ruby - 获取模块中定义的所有常量的值 - 2

    我想获取模块中定义的所有常量的值:moduleLettersA='apple'.freezeB='boy'.freezeendconstants给了我常量的名字:Letters.constants(false)#=>[:A,:B]如何获取它们的值的数组,即["apple","boy"]? 最佳答案 为了做到这一点,请使用mapLetters.constants(false).map&Letters.method(:const_get)这将返回["a","b"]第二种方式:Letters.constants(false).map{|c

  5. ruby-on-rails - 获取 inf-ruby 以使用 ruby​​ 版本管理器 (rvm) - 2

    我安装了ruby​​版本管理器,并将RVM安装的ruby​​实现设置为默认值,这样'哪个ruby'显示'~/.rvm/ruby-1.8.6-p383/bin/ruby'但是当我在emacs中打开inf-ruby缓冲区时,它使用安装在/usr/bin中的ruby​​。有没有办法让emacs像shell一样尊重ruby​​的路径?谢谢! 最佳答案 我创建了一个emacs扩展来将rvm集成到emacs中。如果您有兴趣,可以在这里获取:http://github.com/senny/rvm.el

  6. Ruby 从大范围中获取第 n 个项目 - 2

    假设我有这个范围:("aaaaa".."zzzzz")如何在不事先/每次生成整个项目的情况下从范围中获取第N个项目? 最佳答案 一种快速简便的方法:("aaaaa".."zzzzz").first(42).last#==>"aaabp"如果出于某种原因你不得不一遍又一遍地这样做,或者如果你需要避免为前N个元素构建中间数组,你可以这样写:moduleEnumerabledefskip(n)returnto_enum:skip,nunlessblock_given?each_with_indexdo|item,index|yieldit

  7. ruby - Net::HTTP 获取源代码和状态 - 2

    我目前正在使用以下方法获取页面的源代码:Net::HTTP.get(URI.parse(page.url))我还想获取HTTP状态,而无需发出第二个请求。有没有办法用另一种方法做到这一点?我一直在查看文档,但似乎找不到我要找的东西。 最佳答案 在我看来,除非您需要一些真正的低级访问或控制,否则最好使用Ruby的内置Open::URI模块:require'open-uri'io=open('http://www.example.org/')#=>#body=io.read[0,50]#=>"["200","OK"]io.base_ur

  8. ruby - 没有类方法获取 Ruby 类名 - 2

    如何在Ruby中获取BasicObject实例的类名?例如,假设我有这个:classMyObjectSystem我怎样才能使这段代码成功?编辑:我发现Object的实例方法class被定义为returnrb_class_real(CLASS_OF(obj));。有什么方法可以从Ruby中使用它? 最佳答案 我花了一些时间研究irb并想出了这个:classBasicObjectdefclassklass=class这将为任何从BasicObject继承的对象提供一个#class您可以调用的方法。编辑评论中要求的进一步解释:假设你有对象

  9. ruby-on-rails - 如何在 Gem 中获取 Rails 应用程序的根目录 - 2

    是否可以在应用程序中包含的gem代码中知道应用程序的Rails文件系统根目录?这是gem来源的示例:moduleMyGemdefself.included(base)putsRails.root#returnnilendendActionController::Base.send:include,MyGem谢谢,抱歉我的英语不好 最佳答案 我发现解决类似问题的解决方案是使用railtie初始化程序包含我的模块。所以,在你的/lib/mygem/railtie.rbmoduleMyGemclassRailtie使用此代码,您的模块将在

  10. ruby - 如何使用 CarrierWave 从 S3 获取真实文件 - 2

    我有一个应用程序可以读取文件的内容并为其编制索引。我将它们存储在磁盘本身中,但现在我使用的是AmazonS3,因此以下方法不再适用。事情是这样的:defperform(docId)@document=Document.find(docId)if@document.file?#Youshould'tcreateanewversion@document.versionlessdo|doc|@document.file_content=Cloudoc::Extractor.new.extract(@document.file.file)@document.saveendendend@docu

随机推荐