[英]JavaScript- Events: How To Trigger onClick of underlayed image?
我有两个图像,一个在另一个之上(使用绝对位置)。
只有底层图像定义了 onClick 事件,我想在单击覆盖图像时触发底层图像的 onClick 事件。
我发现对于多个 div 标签,我可以使用stopImmediatePropagation停止这些行为。
但是,默认情况下,图像元素似乎不传播事件。 有什么方法可以用普通的 javascript 打开这些行为或做出反应?
+) 我知道图像绝对定位是一种不好的做法。 我正在创建一个棋盘游戏,您可以在主板图像之上访问一些特殊的地方。 任何建议表示赞赏。
<img className="map" src="map.jpg"></img>
<img className="mission" src="mission.jpg"
style={{react.js part setting top and left}}></img>
.board {
position: relative;
height: auto;
width: 100%;
float: left;
}
.mission {
position: absolute;
height: 10%;
width: auto;
}
由于前面的元素是触发 click 事件的元素,因此您可以将事件处理程序放在该元素上。 然后,在该事件处理程序中,您可以 select 背面图像的 DOM 元素,并使用 JavaScript 在其上触发事件。
一种方法是在 DOM 元素上使用 .click() 方法。
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
let imageInBack = document.getElementById('image-in-back')
let imageInFront = document.getElementById('image-in-front')
imageInFront.addEventListener('click', (e)=>{
e.stopPropagation() //for general purposes, this won't affect theater image
imageInBack.click() //programatically cause the other image to be clicked.
})
由于您似乎正在使用 React,我猜可能有更好的方法来完成您正在尝试做的事情,而不会触发另一个元素上的事件。 但就字面上触发点击事件而言,这是一种方法:
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.imageInBack = React.CreateRef() //gets this variable ready to store a DOM element. See the ref property in the JSX, where the DOM element actually gets assigned to this variable.
}
//the event handler will be assigned to the imageInFront, but it will trigger the DOM element of the image in back:
handleClick(e) {
this.imageInBack.click()
}
render() {
return <div style={{position: 'relative'}}>
<img
ref={(img)=> {this.imageInBack = img}}
className="image-in-back"
style={{position: 'absolute', top: '0px', left: '0px'}}/>
<img className="image-in-front"
style={{position: 'absolute', top: '0px', left: '0px'/>
</div>;
}
}
}
您可以将事件处理程序从背面图像重新分配给正面图像。 确保并取消背面图像上的处理程序:
let imageInBack = document.getElementById('image-in-back')
let imageInFront = document.getElementById('image-in-front')
let events = getEventListeners(imageInBack)
if(events["click"]){
events["click"].forEach((event) => {
imageInFront.addListener('click', event["listener"]);
imageInBack.removeListener('click', event["listener"]);
}
}
我同意其他评论者的观点,如果你使用 React,那么可能有更好的方法来实现这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.