jQuery滚动Div高度

jQuery Scrolling Div Heights

本文关键字:高度 Div 滚动 jQuery      更新时间:2023-09-26

我有一个简单的div头(如下面的代码所示),当我向下滚动时,我不希望窗口本身滚动,但使div高度降低。

<html>
    <head>
        <title>Test</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
        <script src="javascripts/headani.js"></script>
    </head>
    <body>
        <div id="pageTop"></div>
        <div id="pageArticle">
            <div class="siteDesc">
                <p id="hello"></p>
            </div>
        </div>
    </body>
</html>

CSS是:

body {
    margin: 0 0 0 0;
    background-color: beige;
}
#pageTop {
    width: 100%;
    height: 450px;
    background-color: tan;
}
#pageArticle {
    width: 100%;
    height: 1000px;
    background-color: rgba(0,0,0,0);
}
#siteDesc {
    height: 500px;
    background-color: black;
    width: 1000px;
    margin: auto;
}

最后我的jQuery是:(记住这只是一个粗略的模型,一些测试变量可能仍然在那里,所以如果变量没有被使用,或者一个函数没有按预期使用,那么我可以为没有做一些维护而道歉)

$(document).ready( function() {
    var headHeight = $('#pageTop').height();
    $(window).scroll(function() {
        if (headHeight > 50) {
            $(document).bind("scroll", function(e) {
                e.preventDefault;
            })
            headHeight = (headHeight - 1);
            $('#pageTop').css('height', headHeight);
        }
        $('#hello').html($(document).scrollTop() + "<br/>" + headHeight);
    })
});

我得到了它的工作,以尽量减少上下滚动上的div(我将完成使较小的向下滚动和较大的向上滚动),但我的问题是,我不想身体滚动,直到pageTop的高度是50!我只是想知道实现这一点的最好方法是什么?正如你所看到的,我试图绑定滚动,但失败了!

看起来滚动事件在滚动发生后直接触发,所以您不能阻止事件默认操作,因为操作已经发生了(它滚动了)。因此,您可以做的是监听wheel事件和keydown事件以停止操作。

$.fn.scrollEvent = function(handler) {
  this.on('wheel', function(e) {
    handler(e);
  });
  this.on('keydown', function(e) {
    if (e.which === 40) {
      handler(e);
    }
  });
};
$(document).ready(function() {
  var headHeight = $('#pageTop').height();
  window.scrollEvent
  $(window).scrollEvent(function(e) {
    if (headHeight > 50) {
      e.preventDefault();
      e.stopPropagation();
      headHeight = (headHeight - 30);
      $('#pageTop').css('height', headHeight);
    }
    $('#hello').html($(document).scrollTop() + "<br/>" + headHeight);
    return false;
  });
});
body {
  margin: 0 0 0 0;
  background-color: beige;
}
#pageTop {
  width: 100%;
  height: 450px;
  background-color: tan;
}
#pageArticle {
  width: 100%;
  height: 1000px;
  background-color: rgba(0, 0, 0, 0);
}
#siteDesc {
  height: 500px;
  background-color: black;
  width: 1000px;
  margin: auto;
}
<html>
<head>
  <title>Test</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
  <script src="javascripts/headani.js"></script>
</head>
<body>
  <div id="pageTop"></div>
  <div id="pageArticle">
    <div class="siteDesc">
      <p id="hello"></p>
    </div>
  </div>
</body>
</html>