循环浏览突出显示的文本

loop through highlighted text.

本文关键字:文本 显示 浏览 循环      更新时间:2023-09-26

我有一个关于javascript的问题我需要循环浏览用户选择(突出显示的文本)并从 TRL 或 LTR 更改文本方向。这是我做的:

this._execCom("FormatBlock",'<div>');
var node = null;
if (this.area.contentWindow.getSelection) {
    node = this.area.contentWindow.getSelection().anchorNode.parentNode;
}
else if (this.area.contentWindow.document.selection) {
    var range = this.area.contentWindow.document.selection.createRange();
    if (range) {
        node = range.parentElement();
    }
    var walker=this.area.contentWindow.document.createTreeWalker(node, NodeFilter.SHOW_ELEMENT, null, false);
    while (walker.nextNode())
    {
        x=walker.currentNode.tagName;
        if( x == 'DIV')
            walker.currentNode.style.direction="ltr";
    }

这会更改所有div 的方向,即使它们是否在突出显示的文本中,我只需要对用户选择进行更改.

你能帮我吗.

非常感谢

编辑:我误解了你的问题。因此,您只希望用户能够单击并拖动以选择哪些元素应该在 ltr 和 rtl 之间切换"方向"。我有一个使用选择范围的替代方法,在此解决方案中使用它将非常痛苦。

在这里,我使用 jQuery 监听"mousemove"事件,检查鼠标左键是否被按下。如果是这样,我切换方向 css 属性。我还使用自定义数据标志来防止拖动鼠标时元素闪烁。

其中还有一点可以防止选择段落,这可能是您的意图,但我觉得很烦人。如果您希望他们能够选择文本,您可以注释掉/删除该部分。

这是小提琴:http://jsfiddle.net/nbWYK/8/

TL;DNR:

$(document).on("mousemove", 'p', function(e) {
    var $this = $(this);
    if ($this.data('ignore-direction-toggle')) return;
    if (e.which == 1) {
        $this.data('ignore-direction-toggle', true);
        $this.css({
            'direction': ($this.css('direction') == 'ltr' ? 'rtl' : 'ltr')
        });
    }
}).on('mouseleave', 'p', function(e) {
    var $this = $(this);
    if ($this.data('ignore-direction-toggle')) $this.data('ignore-direction-toggle', null);
});