0

我有一个关于 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 的方向,即使它们是否在突出显示的文本中,我只需要对用户选择进行更改。

你能帮我吗 。

非常感谢

4

1 回答 1

0

Edit: I misunderstood your question. So you just want the user to be able to click and drag to select which elements should have the 'direction' toggled between ltr and rtl. I have an alternative to using selection ranges, which will be quite painful to use in this solution.

Here, I use jQuery to listen to 'mousemove' events, checking to see if the left mouse button is depressed. If so, I toggle the direction css attribute. I also use a custom data flag to prevent flickering of the elements as you drag the mouse.

There is also a bit in there to prevent the paragraphs from being selected, which may have been your intention but I found annoying. You can just comment out/remove that part if you want them to be able to select the text.

Here's the fiddle: 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);
});
于 2012-05-14T08:12:44.787 回答