9.点透事件.html 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. /* 触摸行为 */
  12. touch-action: none;
  13. }
  14. #container {
  15. width: 100%;
  16. position: relative;
  17. }
  18. #under {
  19. width: 90%;
  20. height: 500px;
  21. font-size: 24px;
  22. text-align: center;
  23. line-height: 500px;
  24. background: #eee;
  25. margin: 25px auto;
  26. }
  27. #dialog {
  28. width: 80%;
  29. height: 300px;
  30. background: #fff;
  31. position: absolute;
  32. top: 120px;
  33. left: 38px;
  34. z-index: 99;
  35. }
  36. #title {
  37. width: 100%;
  38. height: 200px;
  39. text-align: center;
  40. line-height: 200px;
  41. }
  42. #action {
  43. position: absolute;
  44. top: 200px;
  45. left: 100px;
  46. }
  47. #close {
  48. width: 100px;
  49. height: 35px;
  50. text-align: center;
  51. line-height: 35px;
  52. color: #fff;
  53. background: #00f;
  54. }
  55. #mask {
  56. width: 100%;
  57. background: rgba(0, 0, 0, .5);
  58. position: fixed;
  59. top: 0;
  60. left: 0;
  61. right: 0;
  62. bottom: 0;
  63. }
  64. </style>
  65. </head>
  66. <body>
  67. <div id="container">
  68. <div id="under">底层元素</div>
  69. <div id="dialog">
  70. <div id="title">弹出层</div>
  71. <div id="action">
  72. <div id="close">关闭</div>
  73. </div>
  74. </div>
  75. <div id="mask"></div>
  76. </div>
  77. <script>
  78. var close = document.getElementById("close");
  79. var under = document.getElementById("under");
  80. /**
  81. * 点透事件
  82. * 1.两层元素叠加到一起
  83. * 2.第一层是touch事件
  84. * 3.第二层是click事件或者a标签
  85. *
  86. *
  87. * 解决方案:
  88. * 1.event.preventDefault()
  89. * 2.将click事件全部换成touch
  90. * */
  91. close.ontouchstart = function(event) {
  92. // event.preventDefault();
  93. document.getElementById("dialog").style.display = 'none';
  94. document.getElementById("mask").style.display = 'none';
  95. }
  96. // touchstart => touchmove => touchend
  97. under.onclick = function() {
  98. alert("弹出");
  99. }
  100. </script>
  101. </body>
  102. </html>