我正在尝试构建一个允许人们获取单词或短语(在选择中)的工具,选择部分已完成,但不是单词部分.
当有人点击一个单词时,我需要能够得到当前的单词,我找到了这个解决方案
不幸的是,此代码更改了所有单词并添加了< span>因为我不能在文本中添加html标签(css文件可以导入或动态添加),因此每个单词都会导致我的问题.
如果可能的话,是否有更好的方法来实现这一目标?
EX:
Lorem ipsum dolor sit amet,consectetur adipiscing elit. Donec auctor
ante sit amet nisl consequat volutpat.
如果我点击“坐”,那么我会提醒’坐’
解决方法
那么,对于您的解决方案,您将需要使用选择和双击事件作为一个棘手的事情,并通过doubleclick事件获取生成的范围中的选定单词.
如果您不想引入新标签,则没有其他办法.
尝试这个:
现场演示:http://jsfiddle.net/oscarj24/5D4d3/
- $(document).ready(function() {
- /* set hand cursor to let know the user that this area is clickable */
- var p = $('p');
- p.css({ cursor: 'pointer' });
- /* doubleclick event working with ranges */
- p.dblclick(function(e) {
- var selection = window.getSelection() || document.getSelection() || document.selection.createRange();
- var word = $.trim(selection.toString());
- if(word != '') {
- alert(word);
- }
- /* use this if firefox: selection.collapse(selection.anchorNode,selection.anchorOffset); */
- selection.collapse();
- e.stopPropagation();
- });
- });
希望这可以帮助 :-)