我想要的是顶部(标题)的一个 div,当您第一次加载页面时,它的高度最大(50px),当您向下滚动页面时,我希望高度平滑地降低到最小值高度为 30px。我猜我应该为此使用 jQuery,但我没有那么有经验,所以目前我不知道解决方案。
这是我当前未开发的 HTML 和 CSS:
[HTML]
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/main.css">
</head>
<body>
<!-- Header -->
<div id="header_parent">
</div>
<!-- Body (homepage) -->
<div id="body_parent">
</div>
<!-- Footer -->
<div id="footer_parent">
</div>
</body>
</html>
[CSS]
* {
margin:0 auto;
padding:0;
}
#header_parent {
max-width:1250px;
min-width:750px;
height:50px;
}
明确地说,#header_parent
元素就是我所说的。
我还找到了他们实现这件事的网站:tvgids.tv (不要看内容,我说的是上面的灰色标题。我试着查看源代码,但那并没有给我更多的知识。)
最佳答案
我已经添加到#body_parent 高度以查看滚动条,您可以在创建网站后删除带有高度的那一行。
这是jsfiddle
$(window).on('scroll', function () {
var scrollTop = $(window).scrollTop();
if (scrollTop > 50) {
$('#header_parent').stop().animate({height: "30px"},200);
}
else {
$('#header_parent').stop().animate({height: "50px"},200);
}
});
* {
margin:0 auto;
padding:0;
}
#header_parent {
max-width:1250px;
min-width:750px;
height:50px;
background:#000;
position:fixed;
}
#body_parent {
height:1200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<body>
<!-- Header -->
<div id="header_parent">
</div>
<!-- Body (homepage) -->
<div id="body_parent">
</div>
<!-- Footer -->
<div id="footer_parent">
</div>
</body>
或HTML
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/main.css">
</head>
<body>
<!-- Header -->
<div id="header_parent">
</div>
<!-- Body (homepage) -->
<div id="body_parent">
</div>
<!-- Footer -->
<div id="footer_parent">
</div>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<!-- Your jQuery/Javascript code -->
<script type="text/javascript">
$(window).on('scroll', function () {
var scrollTop = $(window).scrollTop();
if (scrollTop > 50) {
$('#header_parent').stop().animate({height: "30px"},200);
}
else {
$('#header_parent').stop().animate({height: "50px"},200);
}
});
</script>
</body>
</html>
如果您想设置平滑度,请将 200 替换为您的数字,200 平均持续时间(以毫秒为单位)。
$('#header_parent').stop().animate({height: "50px"},200);
关于jquery - 在滚动条上更改 div 高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28676253/