所有
我有两个,部分重叠,顶部有一个类“top”,底部有一个类“bottom”,我想要做的是当我点击重叠区域时触发onclick事件。
我该怎么做?
HTML就像:
.bottom {
width: 300px;
height: 200px;
position: absolute;
background-color: tomato;
left: 100px;
top: 100px;
opacity: 0.5;
}
.top {
width: 300px;
height: 200px;
position: absolute;
background-color: lightseagreen;
left: 200px;
top: 200px;
opacity: 0.8;
}
<div class="bottom"></div>
<div class="top"></div>
我想尝试事件传播,但这种并行结构似乎不适合它。
任何建议和代码示例都将受到赞赏。
答案 0 :(得分:1)
我为你创造了一个傻瓜 - http://plnkr.co/edit/M35aIirycIGZQceU7ppp?p=preview
您必须处理坐标才能实现解决方案。
// Binding click function
$(".bottom, .top").click(function(event){
// Getting bottom and top elements
var bottomElement = $(".bottom");
var topElement = $(".top");
// Getting co-ordinates of click
var x = event.pageX;
var y = event.pageY;
// Calculating bottom element co-ordinates
var bLeft = bottomElement.offset().left;
var bTop = bottomElement.offset().top;
var bRight = bottomElement.width() + bLeft;
var bBottom = bottomElement.height() + bTop;
// Calculating top element co-ordinates
var tLeft = topElement.offset().left;
var tTop = topElement.offset().top;
var tRight = topElement.width() + tLeft;
var tBottom = topElement.height() + tTop;
// Default value as false i.e. click was outside of both the elements
var clickedInsideTop = false;
var clickedInsideBottom = false;
// Check whether the click was inside bottom element
if(x >= bLeft && x <= bRight && y >= bTop && y <= bBottom) {
clickedInsideBottom = true;
}
// Check whether the click was inside top element
if(x >= tLeft && x <= tRight && y >= tTop && y <= tBottom) {
clickedInsideTop = true;
}
// If both conditions are true, that means click was on the overlapping area, now you can do your work, over here showing an alert
if (clickedInsideTop && clickedInsideBottom) {
alert("overlapped area");
}
});
答案 1 :(得分:1)
像往常一样,当我帮助别人时,我会尝试从提供的代码开始。所以你走了:
CSS:
top {
width: 300px;
height: 200px;
position: absolute;
background-color: red;
left: 200px;
top: 200px;
opacity: 0.8;
z-index: 1;
}
.bottom {
width: 300px;
height: 200px;
position: absolute;
background-color: green;
left: 100px;
top: 300px;
opacity: 0.5;
}
DOM:
<div class="top"></div>
<div class="bottom"></div>
JS:
var topClicked = false;
$('.bottom').on('click',function(event) {
$('.top').css('pointer-events', 'auto');
checkIntersection();
});
$('.top').on('click',function(event) {
topClicked = true;
$(this).css('pointer-events', 'none');
$(document.elementFromPoint(event.pageX, event.pageY)).click();
});
function checkIntersection() {
if(topClicked) {
console.log("Intersection click has occured");
}
topClicked = false;
}
答案 2 :(得分:0)
你没有提供代码,所以我也不会。但这是一种开始思考它的方法:
当您单击具有较高z-index的那个(注册单击的那个)时,检查鼠标是否也在较低的范围内。您可以获取较低元素的偏移量(相对于视口)及其大小以检查其区域。
祝你好运。 :)