9_点击穿透.html 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <style>
  9. body{
  10. margin: 0;
  11. }
  12. .container{
  13. width: 100%;
  14. overflow: hidden;
  15. position: relative;
  16. }
  17. .layer-title{
  18. width: 100%;
  19. margin: 50px 0;
  20. text-align: center;
  21. }
  22. .layer-action{
  23. position: absolute;
  24. bottom: 20px;
  25. width: 100%;
  26. text-align: center;
  27. }
  28. .btn{
  29. background-color: aqua;
  30. border: 0;
  31. color: white;
  32. height: 30px;
  33. width: 100px;
  34. line-height: 30px;
  35. }
  36. #underLayer{
  37. background-color: #eee;
  38. width: 90%;
  39. height: 500px;
  40. line-height: 500px;
  41. margin: 30px auto 1000px;
  42. text-align: center;
  43. }
  44. #popupLayer{
  45. background-color: #fff;
  46. width: 80%;
  47. height: 200px;
  48. position: fixed;
  49. top: 50%;
  50. left: 50%;
  51. margin-left: -40%;
  52. margin-top: -100px;
  53. z-index: 1;
  54. }
  55. #mask{
  56. position: fixed;
  57. top: 0;
  58. left: 0;
  59. right: 0;
  60. bottom: 0;
  61. background-color: rgba(0, 0, 0, 0.5);
  62. }
  63. </style>
  64. </head>
  65. <body>
  66. <div class="container">
  67. <div id="underLayer"> 底层元素 </div>
  68. <div id="popupLayer">
  69. <div class="layer-title">弹出层</div>
  70. <div class="layer-action">
  71. <button class="btn" id="close"> 关闭</button>
  72. </div>
  73. </div>
  74. </div>
  75. <div id="mask"></div>
  76. <script>
  77. var oClose = document.querySelector('#close')
  78. var oUnder = document.querySelector('#underLayer')
  79. oClose.ontouchstart = function(e){
  80. //取消事件默认行为
  81. e.preventDefault()
  82. //框隐藏
  83. document.querySelector('#popupLayer').style.display = 'none'
  84. //遮罩层
  85. document.querySelector('#mask').style.display = 'none'
  86. }
  87. // oClose.onclick = function(){
  88. // document.querySelector('#popupLayer').style.display = 'none'
  89. // document.querySelector('#mask').style.display = 'none'
  90. // }
  91. oUnder.onclick = function(){
  92. alert('click')
  93. }
  94. /*
  95. 解决办法:
  96. 1、把上面的事件也换成click事件 这样就不会立即触发 都有延迟
  97. 2、在上层元素的事件中 通过event.preventDefault()取消事件的默认行为
  98. */
  99. /*
  100. 出现点透事件 点击穿透问题
  101. A层覆盖在B层上面,在A层触发touch事件后A层隐藏,会触发B层的click事件
  102. 用户在触摸屏幕的时候 系统会同时产生click和touch事件
  103. 并且 事件流是 touchstart->touchmove->touchend->click
  104. 当用户触摸屏幕时,A层隐藏,300ms后出发了click 但是A层已经没有了
  105. 因此click就落在了B层上面 触发了B层的click事件
  106. */
  107. </script>
  108. </body>
  109. </html>