尤明明Blog

网站建设 | 前端切图,技术不仅是一种专业,更是一种责任!

您的当前位置: 首页 » 前端学习 » js常用代码 »

js手机端判断页面滚动方向展示不同元素

2019-12-26   Umming   js常用代码    评论(0)    浏览(1613)


<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width,initial-scale=1">

	<title>Document</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<body style="height: 6000px;">
    <div class="nav" style="position:fixed; top:0;left:0;width: 100%;height: 60px;background-color: pink;"></div>
   <script type="text/javascript">
var $nav = $('.nav');
  var $result = $('.result');
  
  //页面滚动监听事件
  window.onscroll = function(e){
    $result.html('swipeDown');
    scrollFunc();
    if(scrollDirection == 'down'){
      $nav.css({
        position: 'absolute'
      });
    }
    else if(scrollDirection == 'up'){
      $nav.css({
        position: 'fixed'
      });
    }
  }
  var scrollAction = {x: 'undefined', y: 'undefined'}, scrollDirection;
  
  //判断页面滚动方向
  function scrollFunc() {
    if (typeof scrollAction.x == 'undefined') {
      scrollAction.x = window.pageXOffset;
      scrollAction.y = window.pageYOffset;
    }
    var diffX = scrollAction.x - window.pageXOffset;
    var diffY = scrollAction.y - window.pageYOffset;
    if (diffX < 0) {
    // Scroll right
      scrollDirection = 'right';
    } else if (diffX > 0) {
    // Scroll left
      scrollDirection = 'left';
    } else if (diffY < 0) {
    // Scroll down
      scrollDirection = 'down';
    } else if (diffY > 0) {
    // Scroll up
      scrollDirection = 'up';
    } else {
    // First scroll event
    }
    scrollAction.x = window.pageXOffset;
    scrollAction.y = window.pageYOffset;
  }
   </script> 
</body>
</html>

标签: js代码

本文链接:https://www.umming.com/js/192.html

声明:本站信息由网友自行发布或来源于网络,真实性、合法性由发布人负责,请仔细甄别!本站只为传递信息,我们不做任何双方证明,也不承担任何法律责任。文章内容若侵犯你的权益,请联系本站删除!


发表评论:

//