【问题标题】:jquery get element where the cursor isjquery获取光标所在的元素
【发布时间】:2016-08-06 01:09:21
【问题描述】:

我正在使用 javascript 和 jquery 为我的网站构建一个拆分测试工具。现在,当光标经过预览框中的元素时,我想为每个要拆分的元素显示一个小悬停菜单。有没有可能做这样的事情?我喜欢这样的事情

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

但它只触发一次。因为我不想使用点击,因为我还想在锚元素上显示菜单,所以我有点迷失了

【问题讨论】:

    标签: jquery jquery-plugins


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您可以为此使用document.elementFromPoint

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

      例如:

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

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

      【讨论】:

      • 这也会继续触发一次。而且,当您可以从event 免费获取元素时,为什么有人要使用document.elementFromPoint
      • @Alexander - 在这种特殊情况下,是的。但是对于 OP 的原始问题“jquery get element where the cursor is”-document.elementFromPoint 是要走的路。
      【解决方案3】:

      我相信您想在这里使用mousemove 事件而不是hover 事件。

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

      请记住使用 mousemove 时要格外小心。

      See an example here.

      【讨论】:

        【解决方案4】:

        有 3 种方法可以做到这一点:

        1. 类似的东西:

          $('body').on('mousemove', function() {
           console.log($(':hover').last().attr('name'));
          });
          
        2. 出于调试目的,您可以直接在 chrome 控制台中输入 $(':hover').last() 将鼠标悬停在您想要的位置并按 Enter 运行此控制台命令。

        3. 如果你想一直使用它,我建议不要使用 mousemove 事件。使用类似的东西

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

        【讨论】:

          【解决方案5】:

          试试下面的代码,它会帮助你...

              <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>
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-02-20
            • 2015-01-13
            • 2013-10-12
            • 2023-03-10
            • 2011-03-06
            • 1970-01-01
            相关资源
            最近更新 更多