var scrollToBox = { init: function (obj) { this.selector = obj.selector; this.nowPage = obj.nowPage || 0; this.container = obj.container; this.buttonSelector = obj.buttonSelector; this.getBoxList(); this.bindEvent(); }, getBoxList: function () { this.containerBox = document.querySelector(this.container); this.list = document.querySelectorAll(this.selector); this.totalPage = this.list.length; if (!this.list) { throw new Error("Error in getBoxList: no select dom"); } }, scrollPage: function (pageIndex) { height = this.list[pageIndex].getBoundingClientRect().height; height = pageIndex * height; this.containerBox.scrollTop = height; }, scrollPreviusPage: function () { if (this.nowPage <= 0) { return false; } this.nowPage = this.nowPage - 1; this.scrollPage(this.nowPage); }, scrollNextPage: function () { if (this.nowPage >= this.totalPage - 1) { return false; } this.nowPage = this.nowPage + 1; this.scrollPage(this.nowPage); }, scrollFirstPage: function () { this.nowPage = 0; this.scrollPage(this.nowPage); }, scrollLastPage: function () { this.nowPage = this.totalPage - 1; this.scrollPage(this.nowPage); }, bindEvent: function () { var _this = this; this.btnList = document.querySelectorAll(this.buttonSelector); console.log(this.btnList); this.btnList.forEach(function (item, index) { switch (index) { case 0: item.addEventListener("click", function () { _this.scrollFirstPage(); });break; case 1: item.addEventListener("click", function () { _this.scrollPreviusPage(); }); break; case 2: item.addEventListener("click", function () { _this.scrollNextPage(); }); break; case 3: item.addEventListener("click", function () { _this.scrollLastPage(); });break; } }) } } scrollToBox.init({ container: "#container", selector: "#container li", buttonSelector:'#pagi li button' });
<div id="container"> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul> </div> <ul id="pagi"> <li> <button>首页</button> </li> <li> <button>上一页</button> </li> <li> <button>下一页</button> </li> <li> <button>尾页</button> </li> </ul>
#container { width: 200px; height: 400px; border: 1px dotted black; margin: 50px auto; overflow-y: auto; } #container ul { padding: 0; margin: 0; } #container li { width: 100%; list-style: none; height: 400px; line-height: 400px; text-align: center; margin-bottom: 5px; background: khaki; } #container li:last-child { margin: 0; } #pagi li { float: left; list-style: none; }