2015-11-21 123 views
0

我試圖檢測單擊按鈕時光標的當前位置。但是,我的腳本只能根據文本檢測到光標的位置,不包括html元素。我該如何使這個函數檢測並計算html元素呢?下面的例子。如何讓jquery檢測某個元素中的html元素?

HTML

<div>This is a text</div>  <!-- If cursor is at after the word 'is', 
           position should be 7 --> 
<div><ul><li>This is text with ul and li elements</li></ul></div>  
           <!-- If cursor is at after the word 'is', 
           position should be 15 (counting the ul and li elements) --> 
<button class='button'>Button</button> 

JS

$(document).ready(function() { 
    $('.button').click(function() { 
     var position = window.getSelection().getRangeAt(0).startOffset; 
     alert(position); 
    }); 
}); 

的jsfiddle

http://jsfiddle.net/mjgcyy3x/

回答

1

可能像this

HTML:

<div class="container">This is a text</div> 
<div class="container"><ul><li>There is ul and li elements here</li></ul></div> 
<button class='button'>Button</button> 

的JavaScript:

$(document).ready(function() { 
    $('.button').click(function() { 
     var text = window.getSelection().anchorNode 
     if(text) { 
      var container = $(text).closest(".container"); 
      var htmlLength = container.html().indexOf(text.textContent); 
      var position = window.getSelection().getRangeAt(0).startOffset; 
      alert(htmlLength + position); 
     } 
    }); 
}); 
+0

你是驚人的。非常感謝你。爲了這一天,我的大腦已經破壞了一天。謝謝 – Charas

+0

很高興我能幫忙:) – Arg0n

0

這應該工作:

$(document).ready(function() { 
    $('.button').click(function() { 
     var position = window.getSelection().getRangeAt(0).startOffset; 

     var selection = window.getSelection(); 
     if (selection.rangeCount > 0) { 
      var container = $(selection.getRangeAt(0).startContainer.parentNode).closest('div'); 
      var text = container.text(); 
      var htmlText = container.html(); 
      position += htmlText.indexOf(text); 
     } 

     alert(position); 
    }); 
}); 

jsFiddle

相關問題