js 点击事件如何触发上下层的事件?

  <style>
    #a{
      width: 300px;
      height: 300px;
      background-color: pink;
    }
    #b{
      width: 100px;
      height: 100px;
      background-color: gainsboro;
      position: absolute;
      top: 50px;
      left: 50px;
      pointer-events: none;
    }
  </style>

<body>
  <div id="a">1111111111</div>
  <div id="b">222222222</div>
</body>
</html>
<script>
  document.getElementById('a').addEventListener('click',()=>{
    console.log('a');
  })
  document.getElementById('b').onclick = () => {
    console.log('b');
  }
</script>

当点击b盒子触发b的事件,但是a的事件触发不了,如何使两个盒子都触发呢。

阅读 3.5k
3 个回答

将b放在子级

  <style>
    #a{
      width: 300px;
      height: 300px;
      background-color: pink;

    }
    #b{
      width: 100px;
      height: 100px;
      background-color: gainsboro;
      position: absolute;
      top: 50px;
      left: 50px;

    }
    
  </style>

<body>
  <div id="a">1111111111  <div id="b">222222222</div></div>
</body>
</html>
<script>
  document.getElementById('a').addEventListener('click',()=>{
    console.log('a');
  })
  document.getElementById('b').onclick = () => {
    console.log('b');
  }
</script>

js手动触发

 document.getElementById('a').addEventListener('click', () => {
      console.log('a')
      document.getElementById('b').click()
    })
    document.getElementById('b').onclick = () => {
      console.log('b')
    }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题