如何在javascript中修改文档选择? [英] how to modify the document selection in javascript?

查看:133
本文介绍了如何在javascript中修改文档选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想修改文档选择(当前用鼠标或键盘选择的用户),如何以跨浏览器的方式进行操作?

I wanna modify the document selection (user currently selected by mouse or keyboard), how to do it in a cross browser way?

推荐答案

我没有足够的文本选择来提供真正的帮助,但是你要做的就是做。您将需要查看以下两个函数:

I have not worked with text selection enough to provide real help, but what you are trying to do can be done. You will want to look into the following two functions:


  1. createRange() < a href =http://msdn.microsoft.com/en-us/library/ms536394(VS.85).aspx =noreferrer> MSDN | MDC

  2. getRangeAt() MDC

  1. createRange() MSDN | MDC
  2. getRangeAt() MDC

我知道它可以通过浏览器实现。您可以在此处看到其中的一些内容:

I know it can be implemented cross browser. You can see some of it in action here:

http://fuelyourcoding.com/a-few-strategies-for-using-javascript/

滚动到单击底部并单击使用Evernote脚本的Elephant Icon。但是,我的脚本首先选择主要内容区域(您将看到它呈橙色闪烁),然后在捕获后取消选择。

By scrolling to the bottom and clicking the Elephant Icon, which uses the Evernote script. However, my script first selects the main content area (you will see it flash orange) and then it deselects once the capture is made.

这是一个迷你jQuery插件,可以。它是由我从某个网站改编而来的,就像评论说的那样,我觉得不记得了。注意我将它改编为jQuery非常重要,但代码来自某个网​​站,他们解释了如何做到这一点:

Here is a mini jQuery plugin that does it. It was adapted by me from some site, and like the comments say, I feel horrible for not remembering. Its really important to note I adapted it to jQuery, but the code came from some site where they explained how to do it:

// Adapted this from somewhere. Feel horrible for not remembering.
$.fn.autoSelect = function(){
    var selectTarget = this[0]; // Select first element from jQuery collection
    if(selectTarget != null) {
         if(selectTarget.tagName == 'TEXTAREA' || (selectTarget.tagName == "INPUT" && selectTarget.type == "text")) {
             selectTarget.select();
         } else if(window.getSelection) { // FF, Safari, Opera
             var sel = window.getSelection();
             var range = document.createRange();
             range.selectNode(selectTarget);
             sel.removeAllRanges();
             sel.addRange(range);
         } else { // IE
             document.selection.empty();
             var range = document.body.createTextRange();
             range.moveToElementText(selectTarget);
             range.select();
         };
    };
    return this; // Don't break the chain
};

看来这个脚本在网上有几个地方,但这是另一个变体

这篇关于如何在javascript中修改文档选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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