网页中的锚点如果直接跳转,会给人一种很突然的感觉,添加一个滚动的动画效果会柔和很多。
下面的js代码包含了锚点滚动,页面滚动到一定距离时锚点容器固定(参数fixed),锚点容器垂直偏移量设置(参数offset)
<!DOCTYPE html> <html> <head> <title>网页锚点滚动</title> <meta charset="utf-8"> </head> <style> *{margin: 0;padding: 0;font-family: "Arial";} ul, ol{list-style: none;} .anchor{position: absolute;top: 100px;left: 20px;width: 100px;padding-top: 20px;} .anchor.fixed{top: 0;} .anchor a{display: block;line-height: 50px;background: #123;border-bottom: 1px solid #fff;font-size: 24px;color: #fff;text-align: center;text-decoration: none;} .anchor a.active{background: #fa8000;} .elem{margin-top: 120px;} .elem li{line-height: 50px;margin-bottom: 800px;font-size: 40px;color: #333;text-indent: 150px;} </style> <body> <div class="anchor"> <a href="#anchor-1">1</a> <a href="#anchor-2">2</a> <a href="#anchor-3">3</a> <a href="#anchor-4">4</a> <a href="#anchor-5">5</a> <a href="#anchor-6">6</a> <a href="#anchor-7">7</a> <a href="#anchor-8">8</a> </div> <ul class="elem"> <li id="anchor-1">anchor-1</li> <li id="anchor-2">anchor-2</li> <li id="anchor-3">anchor-3</li> <li id="anchor-4">anchor-4</li> <li id="anchor-5">anchor-5</li> <li id="anchor-6">anchor-6</li> <li id="anchor-7">anchor-7</li> <li id="anchor-8">anchor-8</li> </ul> </body> <script type="text/javascript" src="http://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script> <script> $.fn.anchorScroll = function(option) { return this.each(function() { var options = $.extend({ fixed: 0, offset: 0 }, {}, typeof option === ‘object‘ && option); var $anchorMenu = $(this), $anchorItem = $anchorMenu.find(‘a‘), pageIsScrolling = false; // 点击锚点时页面滚动 $anchorItem.click(function(e) { e.preventDefault ? e.preventDefault() : e.returnValue = false; pageIsScrolling = true; try { var $target = $($(this).attr(‘href‘)); $(‘html, body‘).stop(true, false).animate({ scrollTop: $target.offset().top + options.offset }, function() { pageIsScrolling = false; }); $(this).addClass(‘active‘).siblings().removeClass(‘active‘); } catch (e) {} }); $(window).on(‘scroll DOMContentLoaded load‘, function() { // 固定锚点菜单 if ($(window).scrollTop() > options.fixed) { $anchorMenu.addClass(‘fixed‘).css({ position: ‘fixed‘, marginTop: 0, marginBottom: 0 }); } else { $anchorMenu.removeAttr(‘style‘).removeClass(‘fixed‘); } // 锚点菜单对应项添加高亮样式 if (!pageIsScrolling) { $anchorItem.each(function() { try { var $target = $($(this).attr(‘href‘)); if ($(window).scrollTop() >= $target.offset().top + options.offset) { $(this).addClass(‘active‘).siblings().removeClass(‘active‘); } } catch (e) {} }); } }); }); }; $(‘.anchor‘).anchorScroll({ fixed: 100, offset: -20 }); </script> </html>
时间: 2024-10-13 19:52:29