如何触发底层图片的onClick?

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;
}

您可以将事件处理程序从背面图像重新分配给正面图像。确保并取消背面图像上的处理程序:

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,那么可能有更好的方法来完成此操作。

由于前面的元素是点击事件将被触发的元素,您可以将事件处理程序放在该元素上。然后,在该事件处理程序中,您可以 select 后面图像的 DOM 元素并使用 JavaScript 触发事件。

原版 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 JSX/Class 组件:

由于您似乎在使用 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>;
     }
   }
}