highlight a DOM element on mouse over, like inspect does

心不动则不痛 提交于 2019-11-30 02:22:07

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. Then applying CSS to it is probably most easily done by adding a class to it.

But I wonder if the :hover psuedo-class might save you some trouble...

If not using :hover, here's an example:

(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

$('*').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");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!