2017-04-14 4 views
0

私は自分自身のキャレットを実装しようとしていますが、テキストの先頭で左に行くとDOMの前のテキストノードに移動する必要があります。私の問題は、これはいつも簡単に見つけることができる以前の兄弟だけではないということです。それは親の兄弟の木の底にあるかもしれない。これは私の問題を明確にする必要があります与えられた前に表示されている前のテキストノードを取得するには?

function getPreviousTextElement(node) { 
 
var prev = $('.caret').closest(':text'); 
 
prev.css('color', 'green'); 
 
}
#carot{ 
 
    color:red; 
 
}
<div> 
 
1 <div> 
 
    2 
 
    <div>3</div> 
 
    <div>4</div> 
 
    <div>5 
 
     <div>6</div> 
 
     <div> 
 
     7 
 
     <div>8</div> 
 
     <div>9</div> 
 
     </div> 
 
    </div> 
 
    </div> 
 
</div> 
 
<div> 
 
<span id="carot">|</span>10 
 
</div>

をキャレットが「10」であり、あなたが左キーを押したときだから、「9」に行く必要がありますが、どのように私は、この要素を得るのですか? JSまたはjQuery関数がありますか? jQuery closest()、prevAll()またはparents()は仕事をしていないようです。

+0

を['Node.nextSibling'](https://developer.mozilla.org/en-US/docs/Web/API/Node/nextSibling)とマイナス1の数字です。それから、要素が '$(*:contains(newNum) 'を使って新しい番号に等しい要素を持っています)' – Mohammad

+0

もちろん、テキストノードで 'css'を呼び出すことはあまりできません... –

答えて

0

https://jsfiddle.net/jqb816a1/5/

私はこれまで、いくつかの異なる解決策を試してみました。最初は、DOM要素からの基本的な上向きのトラバーサルが機能すると考えましたが、不幸にも、親要素の不明な数の兄弟をも辿ることを望んだことをあなたの質問で指定してから、ジブ。

すべてのテキストノードを保持するためのSet Objectと、ページ上のテキストノードを含む要素が与えられたときに前のテキストノードを返すメソッドを含むオブジェクトを作成しました。この場合carot

戻りオブジェクトを使用してセットアップ

function findTextNodes(node) { 
    let text_node_set = new Set(); 
    traversal(node); 

    function traversal(node) { 
    check_for_text(node); 
    let ele = node.nextSibling; 
    while (ele) { 
     check_for_text(ele); 
     ele = ele.nextSibling; 
    } 

    } 

    function check_for_text(ele) { 
    if (ele.childNodes) { 
     for (let child of ele.childNodes) { 
     if (child.nodeType == 3 && new RegExp(/\S/g).test(child.textContent)) { 
      text_node_set.add(child); 
     } else { 
      traversal(child); 
     } 
     } 
    } 
    } 

    return { 
    getPrev: function(ele_node) { 
     let text_node; 
     if (ele_node.childNodes) { 
     for (let child of ele_node.childNodes) { 
      if (child.nodeType == 3 && new RegExp(/\S/g).test(child.textContent)) { 
      text_node = child; 
      } 
     } 
     } 
     if (this.text_node_set.has(text_node)) { 
     let prev, previousNode; 
     this.text_node_set.forEach(function(node) { 
      if (node === text_node) { 
      if (prev) previousNode = prev; 
      } 
      prev = node; 
     }) 
     return previousNode; 
     } 
    }, 
    text_node_set 
    } 
} 

のIDを使用してspanタグ:あなたが使用して#のcaret` `の兄弟テキストを取得することができます

let text_nodes = findTextNodes(document.body); 
// object: text_nodes 
// methods: getPrev 
// properties: text_node_set 

let caret = document.getElementById('carot'); 

//print the previous node to the console 
console.log(text_nodes.getPrev(carot)); 

//or turn its text green 
let prevNode = text_nodes.getPrev(carot); 

//(we need to grab the parent node of the text for styling) 
prevNode.parentNode.style.color = "lightGreen"; 
関連する問題