[英]jQuery Scrolling Div Heights
向下滚动时,我有一个简单的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是:(请记住,这只是一个粗略的模型,可能仍然存在一些测试var,因此,如果不使用var或未按预期使用函数,那么我可能为没有做些房子而道歉保持)
$(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! 我只是想知道实现此目标的最佳方法是什么? 如您所见,我尝试绑定滚动,但是失败了!
看起来scroll事件在发生滚动后立即触发,因此您无法阻止事件默认操作,因为该操作已经发生(已滚动)。 因此,您可以做的是侦听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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.