jquery怎么禁止上下滚动事件

文章2022-07-01116 人已阅来源:网络

jquery禁止上下滚动事件的方法:1、打开相应的代码文件;2、判断滚动条高度;3、通过“$(document).bind('mousewheel', function(event, delta)...”禁用滚轮事件即可。

jquery怎么禁止上下滚动事件

本文操作环境:windows7系统、jquery3.2.1版、DELL G3电脑

jquery怎么禁止上下滚动事件?

jQuery禁用、开启鼠标滚轮事件

写一个网页的时候需要刚打开的时候是一个占满一屏的视频,想要禁用鼠标滚轮事件,通过点击向下的按钮使页面向下滑动过视频部分,所以查找了禁用鼠标滚轮的事件方法

1、禁用鼠标滚轮事件

$(document).bind('mousewheel', function(event, delta) {return false;});

之后滑动过视频以后又要使用鼠标滚轮向下滑动,所以解绑事件,使鼠标滚轮可以使用

2、如果要开启鼠标滚轮事件,直接解绑事件就可以了

$(document).unbind('mousewheel');

但是鼠标滚轮可以使用后,向上滚动就会回到视频部分,这时就会很尴尬的发现视频部分既可以用鼠标滚轮也可以用向下按钮,所以滑动到视频部分的时候要禁用鼠标滚轮事件。

怎么判断到了视频部分

1、首先判断我是向上滑动

ps:jQuery 半吊子,所以代码中又有js代码又有jquery代码

window.onscroll = function(){
  p=$(this).scrollTop();
  if(t>p){
    console.log("向上滚动");
  }
  t = p;
};

2、然后判断滚动条高度是否小于页面一屏的高度,这里加了一个获取一屏高度的函数

// 获取浏览器窗口的可视区域的高度
function getViewPortHeight() {
  return document.documentElement.clientHeight || document.body.clientHeight;
}
window.onscroll = function(){
  p=$(this).scrollTop();
  let height = getViewPortHeight();
  if (p >= height){
    $(document).unbind('mousewheel');
  }
  if(t>p){
    if (p < height) {
        $(document).bind('mousewheel', function(event, delta) {
          return false;
        });
        $('html,body').animate({scrollTop:0},1000);
      }
    }
  }
  t = p;
};

但是这样就会无限的给document禁用或开启鼠标滚轮事件,so sad

3、获取事件已经绑定的事件

使用

$._data(obj[0],"event")
var objEvt = $._data($(document)[0], 'events');
window.onscroll = function(){
  p=$(this).scrollTop();
  let height = getViewPortHeight();
  if (p >= height){
    $(document).unbind('mousewheel');
    objEvt = $._data($(document)[0], 'events');
  }
  if(t>p){
    if (p < height) {
      if (!objEvt){
        $(document).bind('mousewheel', function(event, delta) {
          return false;
        });
        objEvt = $._data($(document)[0], 'events');
        $('html,body').animate({scrollTop:0},1000);
      }
    }
  }
  t = p;
};

如果元素已经绑定事件就不绑定了,或者元素绑定了事件就给元素解绑

以上就是jquery怎么禁止上下滚动事件的详细内容!