jquery get element where the cursor is

爱⌒轻易说出口 提交于 2019-12-21 07:07:06

问题


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


回答1:


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.




回答2:


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




回答3:


If you are using the keyboard and not the mouse: Not jQuery, just plain JavaScript for those who are interested:

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



回答4:


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();
     ...
    });
    



回答5:


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>


来源:https://stackoverflow.com/questions/14464293/jquery-get-element-where-the-cursor-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!