简体   繁体   English

javascript-如何使jQuery检测特定元素内的HTML元素?

[英]How to make jquery detect html elements inside a certain element?

I am trying to detect the current position of cursor when button is clicked. 我试图在单击按钮时检测光标的当前位置。 However my script is only able to detect the position of the cursor according to the text, not counting the html elements. 但是我的脚本只能根据文本检测光标的位置,而不能计算html元素。 How do I make this function to detect and count the html elements too ? 我如何使该函数也能检测和计数html元素? Example below. 下面的例子。

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 js

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

Jsfiddle 杰斯菲德尔

http://jsfiddle.net/mjgcyy3x/ http://jsfiddle.net/mjgcyy3x/

Maybe something like this : 也许像这样

HTML: 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: 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);
        }
    });
});

This should work: 这应该工作:

$(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 jsFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM