【发布时间】:2021-06-06 17:04:32
【问题描述】:
我想创建一个小地图。所以我在我的小地图中准确地表示了 div 元素。我希望用户使用小地图浏览网站。
当我在我的小地图(灰色框)内单击时,我得到了正确的位置,但是当我单击“幽灵”或绿色框时,我得到了不正确的尺寸,这导致了不正确的位置设置。
这是一个展示:
function getClickPosition(e) {
// I need the click position of the gray box
// but when I click on the green or red box I get their values
console.log(e.layerX)
}
.minimap {
height: 100px;
width: 140px;
background-color: #999;
position: absolute;
z-index: 100;
}
.viewport-layer {
height: 20px;
width: 35px;
left: 20px;
top: 15px;
box-sizing: border-box;
position: absolute;
border: 2px solid green;
z-index: 101;
max-width: 100px;
}
.ghosty-box {
position: absolute;
top: 60px;
left: 90px;
height: 30px;
width: 40px;
background-color: red;
z-index: 0; // should be in the background
}
<div class="minimap" onclick="getClickPosition(event)">
<!-- user screen: green border -->
<div class="viewport-layer">
</div>
<!-- dynamic size of the minimap -->
<div class="relativeLayer">
<!-- representation of the visible elements -->
<div class="ghosty-box"></div>
</div>
</div>
我的e 控制台说:
click { target: div.ghosty-box, ... layerX: 10, layerY: 11 }
或
click { target: div.viewportLayer, ... layerX: 33, layerY: 16 }
我期待 z-index 会有所帮助。
您对获取.minimap 或.relativeLayer 及其背后元素的点击位置有什么建议吗?
所以target总是是灰色框?
【问题讨论】:
-
我过去遇到的事情是由于元素的嵌套性质,即使您想要点击的是 div,您实际上可能正在点击 P 标签或 A 标签。最好的方法是使用一个看起来不像按钮的按钮,或者只使用一个常规按钮。这有利于用户体验,因为它向他们展示了点击的位置,并且使您的代码更容易,因为您只需聆听按钮按下。
-
那么,无论在小地图内点击什么元素,你想得到那个元素相对于小地图边界的位置? e.target 是否总是必须是小地图?
-
@Kwright02 无需引入不需要的按钮即可处理目标问题的多种其他方法
-
@Kinglish,我只是想要相对位置。价值来自哪里并不重要。我认为通过具有页面尺寸的 div 可以更轻松地工作。
-
@wittgenstein - 看看我更新的答案是否有帮助。
标签: javascript html css dom-events z-index