<!doctype html> <html> <head> <meta charset="utf-8"> <title>ScrollSpy</title> <style> ul, li { margin: 0; padding: 0; list-style: none; } body { color: #666; } .wrap { width: 960px; margin: 0 auto; } .header, .floor { font-size: 35px; height: 960px; padding: 10px 20px; background-color: #ccc; margin-bottom: 20px; } .header { height: 360px; } .nav { position: fixed; top: 35%; right: 50%; margin-right: 500px; width: 60px; background-color: #ccc; } .nav-item { line-height: 26px; padding: 0 10px; border-bottom: solid 1px #ddd; } .nav-item:last-child { border-bottom: none; } .nav-item.active { background-color: #f60; color: #fff; } </style> </head> <body> <div class="wrap"> <div class="header">Header</div> <div class="floor floor-1">Floor 1</div> <div class="floor floor-2">Floor 2</div> <div class="floor floor-3">Floor 3</div> <div class="floor floor-4">Floor 4</div> </div> <ul id="nav" class="nav"> <li class="nav-item">F 1</li> <li class="nav-item">F 2</li> <li class="nav-item">F 3</li> <li class="nav-item">F 4</li> </ul> <script src="http://cdn.bootcss.com/jquery/1.12.1/jquery.js"></script> <script> (function (window, $) { function ScrollSpy(floors, tags, offset) { this.scrollElement = $(window); this.floors = $(floors); this.tags = $(tags); var _offset = (offset === undefined) ? '35%' : offset; if (/^\d+%$/.test(_offset)) { _offset = parseFloat(_offset) / 100; this.offset = this.scrollElement.height() * _offset; this.scrollElement.on('resize', $.proxy(function () { this.offset = this.scrollElement.height() * _offset; }, this)); } else { this.offset = parseFloat(_offset); } this.scrollElement.on('scroll', $.proxy(this.process, this)); this.refresh(); this.process(); } ScrollSpy.prototype = { refresh: function () { this.floorsOffsetTop = this.floors.map(function () { return $(this).offset().top; }).toArray(); }, process: function () { var scrollTop = this.scrollElement.scrollTop() + this.offset, floorsOffsetTop = this.floorsOffsetTop; if (scrollTop < floorsOffsetTop[0]) { this.clear(); return; } for (var i = 0; i < floorsOffsetTop.length; i++) { if (scrollTop > floorsOffsetTop[i] && (floorsOffsetTop[i + 1] === undefined || scrollTop < floorsOffsetTop[i + 1])) { this.activate(i); break; } } }, activate: function (index) { this.clear(); this.tags.eq(index).addClass('active'); }, clear: function () { this.tags.removeClass('active'); } }; window.ScrollSpy = ScrollSpy; })(window, $); new ScrollSpy('.floor', '.nav-item'); </script> </body> </html> 提示:你可以先修改部分代码再运行。 转载请注明:有爱前端 » 电商 商城楼层滚动 喜欢 (0)or分享 (0)