How to check if cursor is between specified tags

2019-08-01 08:12发布

There are some formatted text inside the textarea and a cursor is in some place. I need to check if the cursor is between some specific tags.

Example: foo|bar.

isBetween(['b', 'strong']); // should return true in above case

I have function that returns position of the cursor inside textarea (is has some IE issues, but satisfies me for now). So, all I need is that isBetween() function.

Thanks for any help!

Update:

<p>qwer<b>ty|ui</b>op</p>
isBetween(['p']); // should also return true, because the cursor in not only between 'b', it is between 'p' too

1条回答
做个烂人
2楼-- · 2019-08-01 08:38

 You should enclose the space between the tags with a span tag. Then, in jQuery, use the .mouseover() function.

Example:

<b>TAG1</b>
<span id="spacer">&nbsp;</span>
<strong>TAG2</strong>

<script type="text/javascript">
    $("#spacer").mouseover(function(){
        //Do stuff
    });
</script>

The span has to have something in it, so throw an &nbsp; in there as a space.

Live fiddle example: http://jsfiddle.net/PrruT/

UPDATE:

I'm not going to do the whole function for you, but I'll tell you that you could set it up like this:

/* I'm assuming you can figure out how to get the cursor position on your own, represented by var cursor */

function isBetween(selectorOne, selectorTwo){
    var left = $(selectorOne).position().left; //Left position of the object
    var right = $(selectorTwo).position().left + $(selectorTwo).width(); //Right XY position of the object
    if (cursor > left && cursor < right)
        return true;
    else
        return false;
}
查看更多
登录 后发表回答