8.点透事件.html 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. <style>
  8. * {
  9. margin: 0;
  10. padding: 0;
  11. list-style: none;
  12. text-decoration: none;
  13. box-sizing: border-box;
  14. }
  15. #container {
  16. width: 100vw;
  17. position: relative;
  18. }
  19. #under {
  20. width: 90%;
  21. height: 520px;
  22. color: #fff;
  23. font-size: 28px;
  24. text-align: center;
  25. line-height: 520px;
  26. background: #ccc;
  27. margin: 0 auto;
  28. }
  29. #dialog {
  30. width: 80%;
  31. height: 300px;
  32. background: #fff;
  33. position: absolute;
  34. top: 20%;
  35. left: 40px;
  36. z-index: 99;
  37. }
  38. #title {
  39. font-size: 20px;
  40. width: 100%;
  41. height: 200px;
  42. text-align: center;
  43. line-height: 200px;
  44. }
  45. #btn {
  46. width: 100%;
  47. height: 100px;
  48. }
  49. #close {
  50. width: 100px;
  51. height: 40px;
  52. text-align: center;
  53. line-height: 40px;
  54. color: #fff;
  55. background: #00f;
  56. margin: 0 auto;
  57. }
  58. #mask {
  59. width: 100%;
  60. height: 100vh;
  61. position: absolute;
  62. top: 0;
  63. left: 0;
  64. background:rgba(0,0,0,.3)
  65. }
  66. </style>
  67. </head>
  68. <body>
  69. <div id="container">
  70. <div id="under">底层元素</div>
  71. <div id="dialog">
  72. <div id="title">弹出层</div>
  73. <div id="btn">
  74. <div id="close">关闭</div>
  75. </div>
  76. </div>
  77. <div id="mask"></div>
  78. </div>
  79. <script>
  80. /**
  81. * 点透事件
  82. * 1.两层元素叠加到一起
  83. * 2.第一层是touch事件
  84. * 3.第二层是click事件或者a标签
  85. *
  86. *
  87. * 解决方案:
  88. * 1.event.preventDefault()
  89. * 2.将click事件全部换成touch
  90. * */
  91. let close = document.getElementById("close");
  92. let under = document.getElementById("under");
  93. close.ontouchstart = function(event) {
  94. event.preventDefault();
  95. document.getElementById("dialog").style.display = 'none';
  96. document.getElementById("mask").style.display = 'none';
  97. }
  98. under.onclick = function() {
  99. alert("弹出")
  100. }
  101. </script>
  102. </body>
  103. </html>