在我们写h5 或者移动端网站的时候,通常会有头部下拉这个功能,而当我们下拉的时候,背景body就会被滑动,那么改如何禁止body的滚动尼?
- 通过禁止 touchmove 事件
//js
document.addEventListener('touchmove', function(event) {
event.preventDefault();
}, false);
//jquery
$('body').on('touchmove',function(event){event.preventDefault();});
如果只想禁止下拉框滑动
box.addEventListener('touchmove', function(e){
e.preventDefault()
})
- 通过更改body的样式
某些情况下禁止touchmove 并不能达到我们的要求,那么我们可以试试下面这种方法
//点击出现弹出层
$('.toggle').on('click',function(){
this.bodyScroll=window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
$('body').addClass('no-scroll').css({top : -this.bodyScroll});
})
//关闭弹出层时
$('.close').on('click', function() {
$('body').css("top", "").removeClass('no-scroll');
$(window).scrollTop(this.bodyScroll);
})
body.no-scroll{
position: fixed;
left: 0;
right: 0;
}