但我可以在javascript中获取周围的上下文吗

但我可以在javascript中获取周围的上下文吗

本文介绍了如何获取所选文本,但我可以在javascript中获取周围的上下文吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用以下代码获取用户在网页上选择的文本

I am able to grab the text that a user has selected on a web page,using this code:

function getSelected() {
  var userSelection;
  if (window.getSelection) {
      selection = window.getSelection();
  } else if (document.selection) {
      selection = document.selection.createRange();
  }

}

我可以获得单词围绕
选中的单词。

is it posible for me to get the words around theselected word.

以这些句子为例:如果你需要
framglubble zartbox,那么你应该买红色小部件。
否则你可以买蓝色的小部件,节省一些钱。

Take these sentences for example: "If you need toframglubble the zartbox, then you should buy the red widget.Otherwise you can buy the blue widget and save some money."

我的代码会告诉我这个人是否选择了小部件这个词。
但我想知道选择是在红色还是蓝色之后。这可能是
吗?我一直在互联网上搜索一些建议,并且我在找不到答案时花了b $ b。

My code will tell me if the person has selected the word "widget".But I'd like to know if the selection is after "red" or "blue". Isthis possible? I've been scouring the Internet for some advice, andI'm having trouble finding an answer.

谢谢你的帮助

推荐答案

我编写了快速脚本,可以在选择之前和选择之后识别同一个DIV元素中的部分。

I have written quick script that can identify the part before selection and after selection inside the same DIV element.

但是如果同一个DIV包含多个相同的单词并且你只选择那个单词,那么我写的当前代码无法识别它是第一个还是第二个选定单词所以底线它不会回答你的需求。

However if the same DIV contains the same word more than one time and you select only that word, the current code I wrote can't identify if it's the first or second selected word so bottom line it will not answer your needs.

无论如何,你可以在这里查看/复制/测试代码:只需选择一些内容并查看显示的提醒。

Anyway, you can see/copy/test the code here: http://jsfiddle.net/kvHxJ/ just select something and see the alert that appears.

如果它足以满足您的需求然后很好,接受这个答案继续......否则我需要知道:我们可以假设用户只会选择整个单词,只有一个单词吗?如果答案是肯定的话我确实知道如何解决这个问题。

If it's enough for your needs after all then great, accept this answer and move on... otherwise I need to know: can we assume the user will select whole words only, one word only? If the answer is yes I do have idea how to go around this.

这篇关于如何获取所选文本,但我可以在javascript中获取周围的上下文吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:13