如何使用javascript在页面上选择任意文本? [英] How do I select arbitrary text on the page using javascript?

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

问题描述

假设我有一个contentEditable div ,用户可以编辑和更改其中的文本和元素。如何使用javascript随意更改此 div 中的选择?通过更改我并不是指更改用户选择的内容,我的意思是实际更改选择的。然后,用户应该可以键入选择内容,将其替换为其他内容。

Let's say I have a contentEditable div, to the user can edit and change the text and elements inside it. How do I arbitrarily change the selection in this div with javascript? By "change" I don't mean "change the contents of whatever the user has selected", I mean actually change what is selected. The user should then be able to type over the selection, replacing it with something else.

这应该考虑到我可能想要跨元素选择文本。例如:

This should take into account that I may want to select text across elements. For instance:

<p>Some text <span>goes</span> here.</p>

我可能想要选择Some text go,或者<$ c $里面的所有内容c>< p> 。

I may for instance want to select "Some text go", or everything inside the <p>.

这只需要在Safari / Webkit中使用。

This only needs to work in Safari/Webkit.

提前致谢。作为一个本地代码开发人员,我发现DOM和Javascript一般非常令人沮丧。

Thanks in advance. As a native code developer, I find the DOM and Javascript in general quite frustrating.

推荐答案

除非你需要自己编写,你可能想看看tinyMCE, http://tinymce.moxiecode.com/ ,因为它是一个javascript中的所谓WYSIWYG编辑器。

Unless you need to write your own, you may want to look at tinyMCE, http://tinymce.moxiecode.com/, as it is a nice WYSIWYG editor in javascript.

为了做到这一点,你可能想看看这样的东西:
http://codingtricks.blogspot.com/2009/03/javascript-select-partial -text-in-div.html

In order to do this you will probably want to look at something like this: http://codingtricks.blogspot.com/2009/03/javascript-select-partial-text-in-div.html

这些也可能有所帮助:
JavaScript范围出错
https://developer.mozilla.org/en/DOM/window.getSelection

These may also be helpful: JavaScript ranging gone wrong https://developer.mozilla.org/en/DOM/window.getSelection

您要做的事情将会很复杂,因为您需要选择所选区域,删除所有标签,然后在所选区域中放入所需的标签。

What you are trying to do will be complex, as you will need to take the selected area, remove all the tags, then put in the tag that you want for the selected area.

这篇关于如何使用javascript在页面上选择任意文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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