将选定的文本扩展为整个单词 [英] Get selected text expanded to whole words

查看:70
本文介绍了将选定的文本扩展为整个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在IE中,我可以这样做:

In IE I can do this:

var rng = document.selection.createRange();
rng.expand("word");
txt = rng.text;

我如何在IE之外做相同的操作?

How do I do the equivalent outside of IE?

使用getSelection选择整个单词
建议使用 window.getSelection()。modify(),但我不想修改选择。

Select whole word with getSelection suggested using window.getSelection().modify(), but I don't want to modify the selection.

推荐答案

要恢复您的选择,请执行以下操作:

To restore your selection, do this:

var range = selection.getRangeAt(0); // check for rangeCount in advance
var oldRange = document.createRange();
oldRange.setStart(range.startContainer, range.startOffset);
oldRange.setEnd(range.endContainer, range.endOffset);
...modify the selection and do whatever you need...
selection.removeAllRanges();
selection.addRange(oldRange);

这篇关于将选定的文本扩展为整个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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