我想要实现的是实现“选择检查”类型的功能,就像浏览器所具有的那样。它应该只具有创建一个临时元素的功能,该元素将覆盖在我的鼠标悬停的元素上。
我创建了一个截屏视频来向您展示它应该是什么样子,以及我目前拥有的东西。
我的代码
function create_div(){
let style = `
background-color: rgba(130, 180, 230, 0.5);
outline: solid 1px #0F4D9A;
box-sizing: border-box;
position: absolute;
display: block;
z-index: 999999;
`
let e = document.createElement('DIV')
e.setAttribute('id', 'tester')
e.setAttribute('style', style)
document.body.appendChild( e )
}
create_div()
$( "body" ).mousemove(function( event ) {
$( '#tester' ).css({'display' : 'none'})
let target = $( event.target )
$( '#tester' ).css({'display' : 'block', "width": target.width(),
'height': target .height(), 'top' : target .offset().top,
'left' : target .offset().left});
})
这是我用 jQuery 编写的代码
它在页面上创建一个 DIV,然后在 mousemove
事件中,我设置它的值(高度、宽度和位置)
与我悬停的元素相同。但是,当我将鼠标悬停在上面时,我得到的是一些出现故障的窗口。
我在这里错过了什么?
最佳答案
您需要将 pointer-events: none;
添加到 #tester
的 CSS - 它将使 DIV 对鼠标事件透明。这是为了消除鼠标悬停
为了杀死另一个可能的故障源,让我们把你处理过的最后一个目标保存在某个地方,这样就不需要再次调整大小/重绘#tester
。
它将导致:
function create_div(){
$("body").append(
$("<div id=\"tester\"></div>").css({
"background-color": "rgba(130, 180, 230, 0.5)",
"outline": "solid 1px #0F4D9A",
"box-sizing": "border-box",
"position": "absolute",
"display": "block",
"z-index": "999999",
"pointer-events": "none"
})
);
}
$(document).ready(create_div);
$("body").mousemove(function( event ) {
let target = $(event.target)
if (target.length === 0){
$("#tester").css({
"display" : "none"
});
$("#tester").data("target", null);
}else if(
$("#tester").data("target") === null ||
$("#tester").data("target") !== target
){
$("#tester").data("target", target);
$("#tester").css({
"display" : "block",
"width" : target.width(),
"height" : target.height(),
"top" : target.offset().top,
"left" : target.offset().left
});
}
// else {leave #tester with no changes}
});
关于javascript - 如何修复应使用 CSS 突出显示选定区域的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54028372/