gpt4 book ai didi

javascript - 如何捕获页面主体上的点击

转载 作者:行者123 更新时间:2023-11-28 10:00:44 25 4
gpt4 key购买 nike

我有一个页面,其中有许多 div,当有人单击其中一个时,它会调用 javascript 方法。如果有人单击正文,我还需要能够触发另一个方法调用,这意味着他们没有单击 div,而是单击了 div 之外。当我将 jquery 单击处理程序放在 body 标记上时,即使您单击 div,它也会触发。有人知道我如何限制对 div 之外的任何内容的点击吗?谢谢。

最佳答案

您需要检查点击事件的原始目标。它可以通过 e.target 进行访问,其中 e 是点击事件。

var div = document.getElementById('the-div');

document.body.onclick = function (e) {
var target = e.target;
while (target !== document.body) {
if (target === div) {
// The user clicked inside the div
return;
}
target = target.parentNode;
}

// do the stuff you want when they click outside the div here
};

关于javascript - 如何捕获页面主体上的点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9212992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com