由于窗口大小不一,导致边栏有时过高,有的时候内容不够展示。我们常用方法是边栏随页面滚动。
但在超长页,如果边栏一直跟页面滚动,当用户需要找边栏内容时,就需要滚动很长的距离。
这种用户体验就不好了。
如果边栏一直在边上就会好很多。
查看示例:
https://10.1pxeye.com/docs/fixedsb/
示例源码:
fixedsb.zip
如出现压缩包损坏请尝试使用较新版本的winrar软件。
示例核心js代码:
代码底部有:
$sidebar = $('aside'); // 作用对象
这里,将$(‘aside’)换成您自己的对象就可以了。
(function ($) {
var $body, $window, $sidebar, top = false,
bottom = false,
windowHeight, lastWindowPos = 0,
topOffset = 0,
bodyHeight, sidebarHeight;
function scroll() {
var windowPos = $window.scrollTop();
sidebarHeight = $sidebar.outerHeight();
windowHeight = $window.height();
bodyHeight = $body.height();
if (sidebarHeight > windowHeight) {
if (windowPos > lastWindowPos) {
if (top) {
top = false;
topOffset = ($sidebar.offset().top > 0) ? $sidebar.offset().top : 0;
$sidebar.attr('style', 'top: ' + topOffset + 'px;');
} else if (!bottom && windowPos + windowHeight > sidebarHeight + $sidebar.offset().top && sidebarHeight < bodyHeight) {
bottom = true;
$sidebar.attr('style', 'position: fixed; bottom: 0;');
}
} else if (windowPos < lastWindowPos) {
if (bottom) {
bottom = false;
topOffset = ($sidebar.offset().top > 0) ? $sidebar.offset().top : 0;
$sidebar.attr('style', 'top: ' + topOffset + 'px;');
} else if (!top && windowPos < $sidebar.offset().top) {
top = true;
$sidebar.attr('style', 'position: fixed;');
}
} else {
top = bottom = false;
topOffset = ($sidebar.offset().top > 0) ? $sidebar.offset().top : 0;
$sidebar.attr('style', 'top: ' + topOffset + 'px;');
}
} else if (!top) {
top = true;
$sidebar.attr('style', 'position: fixed;');
}
lastWindowPos = windowPos;
}
$(function () {
$body = $(document.body);
$window = $(window);
$sidebar = $('aside'); // 作用对象
$window.on('scroll', scroll);
scroll();
for (var i = 1; i < 6; i++) {
setTimeout(scroll, 100 * i);
}
});
})(jQuery);
评论区
发表新的留言
您可以留言提出您的疑问或建议。
您的留言得到回复时,会通过您填写的邮箱提醒您。