我正在编写一些模仿大多数浏览器所具有的F12检查工具的代码。将鼠标悬停在元素上时,div会附加半透明的蓝色,表示已选中它:
我遇到的问题是,当光标移动到“检查过”的孩子身上时。在元素中,子元素实际上并没有被悬停:
在悬停之前:
悬停后:
这是我的代码(JS Bin):
$('body *').on('mouseover', function(e) {
if ($(e.target).closest('.inspect_hover').length == 0) {
$('<div class=\'inspect_hover\'></div>').appendTo(e.target);
}
}).on('mouseout', function(e) {
var mouse = [e.pageX, e.pageY];
var min = [$(e.target).offset().left, $(e.target).offset().top];
var max = [($(e.target).offset().left + $(e.target).width()), ($(e.target).offset().top + $(e.target).height())];
if (!(mouse[0] >= min[0] && mouse[0] <= max[0]) || !(mouse[1] >= min[1] && mouse[1] <= max[1])) {
$('div.inspect_hover').remove();
}
});
&#13;
.header {
position: absolute;
width: 400px;
height: 200px;
left: 20px;
top: 20px;
background-color: #efefef;
border: 1px solid rgba(0, 0, 0, 0.125);
}
.header h3 {
position: relative;
display: block;
width: 100%;
height: 40px;
line-height: 40px;
top: 40px;
left: 0px;
text-align: center;
margin: 0px 0px 0px 0px;
}
.inspect_hover {
position: absolute;
width: 100%;
height: 100%;
top: 0px;
left: 0px;
margin: 0px 0px 0px 0px;
background-color: rgba(126, 103, 238, 0.125) !important;
}
&#13;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<div class='header'>
<h3>Hello, World</h3>
</div>
</body>
</html>
&#13;
我如何更改我的JS,以便当将鼠标悬停在孩子上时,子元素也会被检查?
谢谢!
答案 0 :(得分:1)
使用prependTo
代替appendTo
$('body *').on('mouseover', function(e) {
if ($(e.target).closest('.inspect_hover').length == 0) {
$('<div class=\'inspect_hover\'></div>').prependTo(e.target);
}
}).on('mouseout', function(e) {
var mouse = [e.pageX, e.pageY];
var min = [$(e.target).offset().left, $(e.target).offset().top];
var max = [($(e.target).offset().left + $(e.target).width()), ($(e.target).offset().top + $(e.target).height())];
if (!(mouse[0] >= min[0] && mouse[0] <= max[0]) || !(mouse[1] >= min[1] && mouse[1] <= max[1])) {
$('div.inspect_hover').remove();
}
});
&#13;
.header {
position: absolute;
width: 400px;
height: 200px;
left: 20px;
top: 20px;
background-color: #efefef;
border: 1px solid rgba(0, 0, 0, 0.125);
}
.header h3 {
position: relative;
display: block;
width: 100%;
height: 40px;
line-height: 40px;
top: 40px;
left: 0px;
text-align: center;
margin: 0px 0px 0px 0px;
}
.inspect_hover {
position: absolute;
width: 100%;
height: 100%;
top: 0px;
left: 0px;
margin: 0px 0px 0px 0px;
background-color: rgba(126, 103, 238, 0.125) !important;
}
&#13;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<div class='header'>
<h3>Hello, World</h3>
</div>
</body>
</html>
&#13;