简体   繁体   English

在鼠标悬停时突出显示DOM元素,就像inspect一样

[英]highlight a DOM element on mouse over, like inspect does

We have a bookmarklet, and the user clicks a button and an inspect like highligther needs to kick in. We want to this to be cross browser. 我们有一个书签,用户点击一个按钮,像highligther这样的检查需要启动。我们希望这是跨浏览器。

For this we need to detect the DOM element during the mouse move, and once we have this element we need to highlight with CSS. 为此,我们需要在鼠标移动过程中检测DOM元素,一旦我们有了这个元素,我们需要用CSS突出显示。

We have problems detecting the DOM element by mouse move, can you guide us how this is done? 我们在通过鼠标移动检测DOM元素时遇到问题,您能指导我们如何完成这项工作吗?

Once we have this DOM element, on user click we need to extract XPath. 一旦我们有了这个DOM元素,在用户点击时我们需要提取XPath。

You can hook mousemove on document or document.body , then use the target property of the event object to find out the topmost element the mouse is over. 您可以将mousemove挂钩在documentdocument.body ,然后使用event对象的target属性找出鼠标所在的最顶层元素。 Then applying CSS to it is probably most easily done by adding a class to it. 然后通过向其添加类可以最轻松地将CSS应用于它。

But I wonder if the :hover psuedo-class might save you some trouble... 但是我想知道:hover psuedo-class可能会给你带来一些麻烦......

If not using :hover , here's an example: 如果不使用:hover ,这是一个例子:

(function() {
  var prev;

  if (document.body.addEventListener) {
    document.body.addEventListener('mouseover', handler, false);
  }
  else if (document.body.attachEvent) {
    document.body.attachEvent('mouseover', function(e) {
      return handler(e || window.event);
    });
  }
  else {
    document.body.onmouseover = handler;
  }

  function handler(event) {
    if (event.target === document.body ||
        (prev && prev === event.target)) {
      return;
    }
    if (prev) {
      prev.className = prev.className.replace(/\bhighlight\b/, '');
      prev = undefined;
    }
    if (event.target) {
      prev = event.target;
      prev.className += " highlight";
    }
  }

})();

Live copy | 实时复制 | source 资源

With the help of jquery you can do something like this 在jquery的帮助下,你可以做这样的事情

$('*').hover(
    function(e){
        $(this).css('border', '1px solid black');
        e.preventDefault();
        e.stopPropagation();
        return false;
    },function(e){
        $(this).css('border', 'none');
        e.preventDefault();
        e.stopPropagation();
        return false;
    }
);

With this code in your bookmarklet, you can load what ever code 使用您的书签中的此代码,您可以加载任何代码

javascript:function loadScript(src){f=document.createElement('script');if(f){f.setAttribute("type","text/javascript");f.setAttribute("src",src);document.getElementsByTagName("head")[0].appendChild(f);}};loadScript("yourscripturl");

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

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