简体   繁体   中英

jquery get element where the cursor is

I'm building a splittesting tool for my website with javascript and jquery. Now I want to show for each elements I want to splittest a little hovermenu when the cursor passes over the element in my previewbox. Is there any possibility to do something like this ? I treid something like this

$('body').hover(function(event){
    console.log(event.target.nodeName);
    // to see if it's showing up the element   
});

but it's only triggering once. As I don't want to use click since I want also to showup the menu on anchor elements I'm a bit lost

I believe you want to use the mousemove event here instead of the hover event.

$('body').mousemove(function(evt){
    console.log(evt.target);
});

Just remember to use mousemove with extreme caution.

See an example here.

You can use document.elementFromPoint for this.

var element = document.elementFromPoint(x, y);

For ex:

$('body').hover(function(event){
    var el = document.elementFromPoint(event.pageX, event.pageY);
});

Docs: https://developer.mozilla.org/en-US/docs/DOM/document.elementFromPoint

如果您使用的是键盘而不是鼠标:不是jQuery,只对那些感兴趣的人使用简单的JavaScript:

getSelection().getRangeAt(0).commonAncestorContainer.parentNode

Try the below coding it will help you...

    <body onMouseMove="javaScript:mouseEventHandler(event);">

    <script>
    function mouseEventHandler(mEvent) {
// Internet Explorer
                alert(mEvent.srcElement.nodeName); //Display Node Name
                alert(mEvent.srcElement.id); //Display Element ID
//FireFox
                alert(mEvent.target.nodeName);//Display Node Name
                alert(mEvent.target.id);//Display Element ID
            }
    </script>

There are 3 ways to do so:

  1. Something like that:

     $('body').on('mousemove', function() { console.log($(':hover').last().attr('name')); }); 
  2. For debugging purpose you can jush type in chrome console $(':hover').last() Than hover mouse where you want and press Enter to run this console command.

  3. If you want to use it constatly, I recommend not to use mousemove event. Use something like that

     $('.one_of_your_trigger_element').on('mouseenter', function() { var hover_element = $(':hover').last(); ... }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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