Javascript:如何根据html标签扩展用户选择? [英] Javascript: How do I expand a user selection based on html tags?

查看:75
本文介绍了Javascript:如何根据html标签扩展用户选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Le Code:
http://jsfiddle.net/frf7w/12/

所以现在,当前方法将所选文本完全视为...选中,并添加标签,以便在显示时,页面不会吹起来。

So right now, the current method will take the selected text exactly as... selected, and add tags so that when it is displayed, the page doesn't blow up.

但我想做的是:
当用户选择页面的一部分时,如果选择中有不匹配的标签,选择将向前或向后跳转(取决于选择中不匹配的标签)到使选择有效的标签的标签。

But what I want to do: Is to, when a user selects a portion of a page, if there are un-matched tags within the selection, the selection will either jump forward or backward (depending on what unmatched tag is in the selection) to the tag(s) that make the selection valid html.

之所以如此我想这样做是因为我希望用户能够在页面上选择文本,并且能够在WYSIWYG编辑器中编辑该文本(我现在可以使用链接代码执行此操作),然后将它们放入已经编辑回页面(目前无法执行此操作,因为我使用的方法添加了标签)。

The reason why I want to do this, is because I want a user to be able te select text on a page, and be able to edit that text in a WYSIWYG editor (I can currently do this with the linked code), and then put what they've edited back into the page (currently can't do this, because the method I use adds tags).

推荐答案

你可以通过添加范围来更改选择的边界:

You can change the boundaries of the selection by adding a range:

var sel = window.getSelection(),
    range = sel.getRangeAt(0);

var startEl = sel.anchorNode;
if (startEl != range.commonAncestorContainer) {
    while (startEl.parentNode != range.commonAncestorContainer) {
        startEl = startEl.parentNode;
    }
}
var endEl = sel.focusNode;
if (endEl != range.commonAncestorContainer) {
    while (endEl.parentNode != range.commonAncestorContainer) {
        endEl = endEl.parentNode;
    }
}

range.setStartBefore(startEl);
range.setEndAfter(endEl);

sel.addRange(range);

以上示例将为您提供一个选择,该选择将展开以覆盖整个树之间的开始和端节点,包括端点(感谢 commonAncestorContainer() )。

The above example will give you a selection that is expanded to cover the entire of the tree between the start and end nodes, inclusive (thanks to commonAncestorContainer()).

这会将文本节点视为等于dom元素,但这对您来说应该不是问题。

This treats text nodes as equal to dom elements, but this shouldn't be a problem for you.

演示: http://jsfiddle.net/Nq6hr/2/

这篇关于Javascript:如何根据html标签扩展用户选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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