选择文本,然后使用 jQuery for AJAX 将其分成三部分

发布于 2024-10-15 03:18:49 字数 2149 浏览 4 评论 0原文

我想在容器(DIV)中获取一堆 HTML,然后让用户选择其中的一部分。它不是我正在寻找的“可编辑区域”。因为我们不希望用户能够覆盖/更改文本。只需标记它即可。

用户选择它后,我想知道选择了什么,但也想知道所选部分在哪里。

例如。

  1. 我们有一个项目符号列表,用户选择项目符号 3 和 4。

  2. 我们有一些标题1和三个段落。然后用户选择中间段落的一部分。我想知道该段落的位置。

我进行了一些研究,据我了解,MSIE 在选择方面存在问题,如果涉及到选择的 startPos 和 endPos 的话。

其次,如果标记的文本在整个容器内多次出现怎么办?

这是一个例子:

<div id="markable">

   <h1>Here is a nice headline</h1>

   <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque non
      tempor metus. Ut malesuada posuere nunc eu venenatis. Donec sagittis tempus
      neque, tempus iaculis sapien consectetur id.</p>

  <p>Nulla tempus porttitor pellentesque. Curabitur cursus dictum felis quis tempus.
     Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia
     Curae; Quisque fringilla massa id libero commodo venenatis.</p>

  <ol>
     <li>here is a bullet line #1</li>
     <li>here is a bullet line #2</li>
     <li>here is a bullet line #3</li>
     <li>here is a bullet line #4</li>
     <li>here is a bullet line #5</li>
     <li>here is a bullet line #6</li>
  </ol>

  <h2>here is a sub-headline</h2>

  <p>Aenean auctor fringilla dolor. Aenean pulvinar tortor sed lacus auctor cursus.
     Sed sit amet imperdiet massa. Class aptent taciti sociosqu ad litora torquent
     per conubia nostra, per inceptos himenaeos. Fusce lectus neque, rhoncus et
     malesuada at, blandit at risus. Vivamus rhoncus ante vel erat mollis 
     consequat.</p>

</div>

问题就在这里,如果用户选择“tempus”,它不足以知道这个词,我还需要知道哪个词(什么段落/标题/项目符号元素)这是。

原因是我们希望“读者”能够发现感兴趣/关注的事物。有时是整个段落,有时只是一个单词或标题。

完美的解决方案

是,如果我们能够以某种方式检测到 DOM 中的哪个“元素”(我猜是从顶部计数)被选中。其次,该特定元素内有多少(起点和终点)。

因为这样我们就可以对我们的 ASP.NET 执行某种 Ajax,告诉后端已标记的内容,然后执行任何操作...

我发现一些在线代码编辑器可以执行上述操作 + 很多超出了需要,但相信这个解决方案要简单得多。只是找不到开始使用 jQuery 解决方案的正确方法。

希望 jQuery Yoda 能读到这篇文章。 :-)

I would like to take a bunch of HTML inside a container(DIV) then let the user select part of it. Its not an "editable area" that I am looking for. As we dont want the user to be able to overwrite/change the text. Just mark it.

After the user has selected it, I would like to know what was selected BUT also WHERE that selected part IS.

Eg.

  1. We have a bullet list and the users selects bulletline 3 and 4.

  2. We have some Headline1 and three paragraphs. Then the user selectes part of the middle paragraph. I would like to know where in that paragraph.

I've research a little and from what I understand MSIE has a problem with selection, if it comes to the startPos and endPos of the selection.

Secondly, what if the marked text is multiple times inside the whole container?

Here is an example:

<div id="markable">

   <h1>Here is a nice headline</h1>

   <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque non
      tempor metus. Ut malesuada posuere nunc eu venenatis. Donec sagittis tempus
      neque, tempus iaculis sapien consectetur id.</p>

  <p>Nulla tempus porttitor pellentesque. Curabitur cursus dictum felis quis tempus.
     Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia
     Curae; Quisque fringilla massa id libero commodo venenatis.</p>

  <ol>
     <li>here is a bullet line #1</li>
     <li>here is a bullet line #2</li>
     <li>here is a bullet line #3</li>
     <li>here is a bullet line #4</li>
     <li>here is a bullet line #5</li>
     <li>here is a bullet line #6</li>
  </ol>

  <h2>here is a sub-headline</h2>

  <p>Aenean auctor fringilla dolor. Aenean pulvinar tortor sed lacus auctor cursus.
     Sed sit amet imperdiet massa. Class aptent taciti sociosqu ad litora torquent
     per conubia nostra, per inceptos himenaeos. Fusce lectus neque, rhoncus et
     malesuada at, blandit at risus. Vivamus rhoncus ante vel erat mollis 
     consequat.</p>

</div>

The problem is here if the user selects "tempus" its not good enough to know the word, I also need to know WHICH of the words (what paragraph/headline/bullet element) it is.

Reason is that we want "readers" to be able to spot things of interest/attention. Sometimes whole paragraphs, sometimes just a single word or headline.

The perfect solution

would be if we somehow could detect in which "element" (counting from top I guess) in the DOM that is selected. Secondly how much (start and end point) inside that particular element.

Because then we could do some sort of Ajax back to our ASP.NET which tells the backend what has been marked and then do what ever ...

I've found some online-code editors that does a BUNCH of the above + a lot more than needed, but believe the solution is much more simple on this one. Just cant find the proper way to get started with a jQuery solution.

In hope of a jQuery Yoda reading this. :-)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

另类 2024-10-22 03:18:49

抱歉,这只是部分答案,这将为您提供在所有浏览器中选择开始和结束的元素的索引,但选择开始和结束的偏移量仅在 Gecko 和 WebKit 浏览器中有效。 IE 只支持 TextRange 对象,这对我来说有点神秘,而且使用起来有点痛苦(这个答案底部的链接有一个覆盖所有浏览器的实现示例)

这个解决方案返回元素的索引选择包含(相对于您的 #markable 容器)以及开始和结束选择的索引(相对于它们的包含节点)。

在此示例中,我使用事件来捕获包含选择的元素(这可以解决浏览器差异),但是您也可以在没有事件的情况下轻松执行此操作(对于 Firefox、Opera、Chrome 和 Safari),因为 Range 对象为您提供了anchorNode 和focusNode 分别是选择开始和结束的 DOM 节点(更多信息请参见 http://www .quirksmode.org/dom/range_intro.html

<html>
<head>

  <script src="http://code.jquery.com/jquery-1.4.4.js"></script>
  <script>

  var end;
  var start;

  indexes = new Array();
var endIndex;
  var startIndex;
  $(document).ready(function(){


$("#markable").mouseup(function(event){
end = event.target;

indexes.push($("*", "#markable").index($(end)));
//normalize start and end just in case someone selects 'backwards' 
indexes.sort(sortASC);




event.stopPropagation()
})

$("#markable").mousedown(function(event){
indexes.length=0;
start = event.target;
event.stopPropagation()
indexes.push($("*", "#markable").index($(start)));
})

$(".button").click(function(){

sel = getSel();

alert("Index of the element selection starts in (relative to #markable): "+indexes[0] +"\n" + 
"Index of the of the beginning of selection in the start node: "+ sel.anchorOffset+"\n" + 
"Index of the element selection ends in  (relative to #markable): "+ indexes[1]+"\n"+ 
"Index of the of the end of selection in the end node: "+ sel.focusOffset)

})

  })




function sortASC(a, b){ return (a-b); }
function sortDESC(a, b){ return (b-a); }

function getSel()
{
    var txt = '';
     if (window.getSelection)
    {
        txt = window.getSelection();
             }
    else if (document.getSelection)
    {
        txt = document.getSelection();
            }

    else if (document.selection)
    {
        txt = document.selection.createRange();
            }
    else return;
return txt;
}
</script>

</head>
<body>
<div id="markable">

   <h1>Here is a nice headline</h1>

   <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque non
      tempor metus. Ut malesuada posuere nunc eu venenatis. Donec sagittis tempus
      neque, tempus iaculis sapien consectetur id.</p>

  <p>Nulla tempus porttitor pellentesque. Curabitur cursus dictum felis quis tempus.
     Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia
     Curae; Quisque fringilla massa id libero commodo venenatis.</p>

  <ol>
     <li>here is a bullet line #1</li>
     <li>here is a bullet line #2</li>
     <li>here is a bullet line #3</li>
     <li>here is a bullet line #4</li>
     <li>here is a bullet line #5</li>
     <li>here is a bullet line #6</li>
  </ol>

  <h2>here is a sub-headline</h2>

  <p>Aenean auctor fringilla dolor. Aenean pulvinar tortor sed lacus auctor cursus.
     Sed sit amet imperdiet massa. Class aptent taciti sociosqu ad litora torquent
     per conubia nostra, per inceptos himenaeos. Fusce lectus neque, rhoncus et
     malesuada at, blandit at risus. Vivamus rhoncus ante vel erat mollis 
     consequat.</p>

</div>
<input type=button class=button value="Get selection data">


</body>
</html>

这里有一个链接,它将为您提供更多跨浏览器解决方案(向下滚动到示例 2)
http://help.dottoro.com/ljjmnrqr.php

编辑:对于 IE,您需要使用document.body.createTextRange() 获取文本范围。我仍然不确定如何获得相当于anchorOffset的内容,但以下链接可能会有所帮助:
http ://bytes.com/topic/javascript/answers/629503-ie-selection-range-set-range-start-click-position-get-char-offset

Sorry this is only a partial answer this will give you indexes of elements in which the selection starts and ends in all browsers, but the offsets of the beginning and end of selection will only work in Gecko and WebKit browsers. IE only supports a TextRange object which is a bit of a mystery to me and a bit of a pain to work with (the link at the bottom of this answer has an example of implementation covering all browsers)

This solution returns indexes of elements that the selection contains (in relation to your #markable container) and indexes of start and end selection (in relation to their containing nodes).

In this example I am using events to capture the elements which contain the selection (this gets around browser differences) but you can easily do this without events as well (for Firefox, Opera, Chrome and Safari) as the Range object gives you anchorNode and focusNode which are the DOM nodes in which the selection starts and ends respectively (more info here http://www.quirksmode.org/dom/range_intro.html)

<html>
<head>

  <script src="http://code.jquery.com/jquery-1.4.4.js"></script>
  <script>

  var end;
  var start;

  indexes = new Array();
var endIndex;
  var startIndex;
  $(document).ready(function(){


$("#markable").mouseup(function(event){
end = event.target;

indexes.push($("*", "#markable").index($(end)));
//normalize start and end just in case someone selects 'backwards' 
indexes.sort(sortASC);




event.stopPropagation()
})

$("#markable").mousedown(function(event){
indexes.length=0;
start = event.target;
event.stopPropagation()
indexes.push($("*", "#markable").index($(start)));
})

$(".button").click(function(){

sel = getSel();

alert("Index of the element selection starts in (relative to #markable): "+indexes[0] +"\n" + 
"Index of the of the beginning of selection in the start node: "+ sel.anchorOffset+"\n" + 
"Index of the element selection ends in  (relative to #markable): "+ indexes[1]+"\n"+ 
"Index of the of the end of selection in the end node: "+ sel.focusOffset)

})

  })




function sortASC(a, b){ return (a-b); }
function sortDESC(a, b){ return (b-a); }

function getSel()
{
    var txt = '';
     if (window.getSelection)
    {
        txt = window.getSelection();
             }
    else if (document.getSelection)
    {
        txt = document.getSelection();
            }

    else if (document.selection)
    {
        txt = document.selection.createRange();
            }
    else return;
return txt;
}
</script>

</head>
<body>
<div id="markable">

   <h1>Here is a nice headline</h1>

   <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque non
      tempor metus. Ut malesuada posuere nunc eu venenatis. Donec sagittis tempus
      neque, tempus iaculis sapien consectetur id.</p>

  <p>Nulla tempus porttitor pellentesque. Curabitur cursus dictum felis quis tempus.
     Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia
     Curae; Quisque fringilla massa id libero commodo venenatis.</p>

  <ol>
     <li>here is a bullet line #1</li>
     <li>here is a bullet line #2</li>
     <li>here is a bullet line #3</li>
     <li>here is a bullet line #4</li>
     <li>here is a bullet line #5</li>
     <li>here is a bullet line #6</li>
  </ol>

  <h2>here is a sub-headline</h2>

  <p>Aenean auctor fringilla dolor. Aenean pulvinar tortor sed lacus auctor cursus.
     Sed sit amet imperdiet massa. Class aptent taciti sociosqu ad litora torquent
     per conubia nostra, per inceptos himenaeos. Fusce lectus neque, rhoncus et
     malesuada at, blandit at risus. Vivamus rhoncus ante vel erat mollis 
     consequat.</p>

</div>
<input type=button class=button value="Get selection data">


</body>
</html>

And here is a link which will give you more of a cross browser solution (scroll down to example 2)
http://help.dottoro.com/ljjmnrqr.php

EDIT: For IE you need to use document.body.createTextRange() to get a text range. I am still not sure how you get the equivalent of anchorOffset but the following link might be helpful:
http://bytes.com/topic/javascript/answers/629503-ie-selection-range-set-range-start-click-position-get-char-offset

留蓝 2024-10-22 03:18:49

这是一个跨浏览器库,可以满足您的所有需求
http://code.google.com/p/rangy/

Here is a cross browser library that will do all you want for you
http://code.google.com/p/rangy/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文