jQuery插件ScrollUpBar Plugin实现下滑隐藏/上滑显示网站导航菜单栏。
使用方法
引用js
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
PS:使用前检测网站是否有jquery.js文件。
插件js
(function($) {
'use strict';
$.fn.scrollupbar = function() {
var $window = $(window),
$document = $(document),
$topbar = this,
topbarHeight = $topbar.outerHeight(),
lastY = 0, // Keep track of the last Y to detect scroll direction.
revealing = false, // Indicate if the bar's reveal is in progress.
timeout;
$window.scroll(function() {
var y = $window.scrollTop();
// Cancel the event fired by the previous scroll.
if (timeout) {
clearTimeout(timeout);
}
// Ignore elastic scrolling.
if (y < 0 || y > ($document.height() - $window.height())) {
return;
}
if (y < lastY) { // Scrolling up
// The first scroll up places the bar right above the top frame.
if (!revealing) {
revealing = true;
if (y > topbarHeight) {
$topbar.css('top', y - topbarHeight);
}
}
// Scrolls up bigger than the bar's height fixes the bar on top.
if (parseInt($topbar.css('top')) > y) {
$topbar.css({
'position': 'fixed',
'top': 0
});
}
// Fire an event to reveal the entire bar after 400ms if the scroll
// wasn't big enough.
timeout = setTimeout(function() {
if (y < parseInt($topbar.css('top')) + topbarHeight) {
$topbar.css({
'position': 'fixed',
'top': parseInt($topbar.css('top')) - y
});
$topbar.animate({'top': 0}, 100);
}
}, 400);
} else { // Scrolling down
revealing = false;
// The first scroll down unfixes the bar allowing it to scroll with the
// page.
if ($topbar.css('position') == 'fixed') {
$topbar.css({
'position': 'absolute',
'top': y
});
}
// Fire an event to hide the entire bar after 400ms if the scroll
// wasn't big enough.
timeout = setTimeout(function() {
if (y < parseInt($topbar.css('top')) + topbarHeight) {
if (y > topbarHeight) {
$topbar.animate({'top': y - topbarHeight}, 100);
}
}
}, 400);
}
lastY = y;
});
return this;
};
})(jQuery);
PS:复制上方代码,创建js文件,应用到对于页面。
html代码
<div class="top">
固定菜单栏
</div>
<div class="nav" >
隐藏菜单栏
</div>
<div class="text">
内容显示区
</div>
PS:测试内容显示区域记得填充多一点内容才能看到效果
css代码
*{padding: 0;margin: 0;text-align: center}
.nav{width: 100%; background-color:blue; color:#fff; font-size:24px; padding:5px;
position: fixed; top:0; left:0;right: 0;
}
.text{}
适用于网站导航栏,菜单栏,栏目栏,话题栏,还有更多玩法....大家慢慢研究。
广告插入