javascript 在鼠标悬停时突出显示 DOM 元素,就像检查一样
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11010569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
highlight a DOM element on mouse over, like inspect does
提问by Ionut Flavius Pogacian
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。
回答by T.J. Crowder
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.
您可以勾mousemove
上document
或document.body
,然后使用target
事件对象的属性来找出鼠标移动到最顶端的元素。然后将 CSS 应用到它可能最容易通过向它添加一个类来完成。
But I wonder if the :hover
psuedo-class might save you some trouble...
不过不知道:hover
伪级能不能省点麻烦……
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";
}
}
})();
回答by Trinh Hoang Nhu
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");