事件冒泡?移动端如何阻止触摸滑动事件冒泡,一个节点可滑动而不影响body节点的滑动
准确的说:应该是锁定背景滚动
描述:原body内容的高度已经超过了手机屏的可视区域的好几倍了,这时候点击某个按钮,出现一个弹出层,固定定位在底部,有一定的高度,超过高度内容可滚动,当滚动到底部时,或者内容并没有高过弹出层的高度,向上或向下都会给原本body里的内容产生滚动,这并不是我们想要的效果。
图文分析:
产生问题的原因:我觉得是因为定位导致了元素脱离标准流,而产生body的滚动,并不是事件的冒泡机制。
如果您有异议,欢迎评论留言,一起探讨
下面说说解决的方式:
如果觉得阻止事件冒泡能解决这个问题,那么你就 使用 e.stopPropagation() 把
正确的解决方式: 给body添加 overflow:hidden;
下面附一下示例代码:
简单示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.item {
height: 300px;
border: 1px solid red;
}
.popup {
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
z-index: 99999;
background-color: rgba(0, 0, 0, 0.75);
}
.popup-content {
position: fixed;
z-index: 111111;
border-radius: 15px 15px 0 0;
left: 0;
bottom: 0;
right: 0;
}
.none{
display: none;
}
</style>
</head>
<body>
<input type="button" value="点击" id="btn">
<div class="box">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="dialog none">
<div class="popup"></div>
<div class="popup-content">
<div style="height:200px;overflow:auto;background-color: white;">
<div>
<p style="line-height: 40px;">2</p>
<p style="line-height: 40px;">2</p>
<p style="line-height: 40px;">2</p>
<p style="line-height: 40px;">2</p>
<p style="line-height: 40px;">2</p>
<p style="line-height: 40px;">2</p>
</div>
</div>
</div>
</div>
</div>
</body>
<script>
document.querySelector('#btn').addEventListener('click',function(){
document.querySelector('.dialog').classList.remove('none')
document.body.style.overflow = "hidden" // 如果不加这一步,则会触发body的滚动
})
</script>
</html>
高级示例代码:
如下操作:
至于源码目前还在更新中,自己看把