实现列表滚动的插件事例。
* { margin: 0; padding: 0; } .panel { overflow: hidden; margin: 100px auto; padding: 0 30px; width: 300px; height: 200px; border: 1px solid #ddd; } .scroll-demo { position: relative; }
<div class="panel"> <ul id="wrap" class="scroll-demo"> <li>我要滚动了1</li> <li>我要滚动了2</li> <li>我要滚动了3</li> <li>我要滚动了4</li> <li>我要滚动了5</li> <li>我要滚动了6</li> <li>我要滚动了7</li> <li>我要滚动了8</li> <li>我要滚动了9</li> <li>我要滚动了10</li> <li>我要滚动了11</li> <li>我要滚动了12</li> <li>我要滚动了13</li> </ul> </div>
滚动插件代码
var TimeScroll = (function() { var timeScrollFun = function() {}; /** * 初始化 * @param {[type]} params [description] * @return [description] */ timeScrollFun.prototype.init = function(config) { this.t = ''; this.d = 1; this.o = ''; this.$wrap = $('#' + config.id); _bindHover(this); return this; }; /** * 滚动时间轴 * @param {[type]} params [description] * @return [description] */ timeScrollFun.prototype.scrollList = function() { var _this = this; _scroll(_this); }; /** * 重置滚动 * @param {[type]} params [description] * @return [description] */ timeScrollFun.prototype.reset = function() { this.t && clearInterval(this.t); this.t = ''; this.o && clearTimeout(this.o); this.o = ''; this.$wrap.css('top', '0'); }; /** * 滚动 * @param {[type]} params [description] * @return [description] */ var _scroll = function(_this) { _this.t = setInterval(function() { var $wrap = _this.$wrap, listHeight = $wrap.height(), pHeight = $wrap.parent().height(), diff = listHeight - pHeight, top = Number($wrap.css('top').replace('px', '')); if (diff <= 0) { _this.t && clearInterval(_this.t); _this.t = ''; return false; } if (_this.d > 0) { // 向上滚动 var gdjl = top * -1; if (diff <= gdjl) { // 向上滚动到顶部,停止5s后向下滚动 _this.t && clearInterval(_this.t); _this.t = ''; _this.o = setTimeout(function() { _this.d = -1; _scroll(_this); }, 2000); } else { // 继续向上滚动 top = top - 1; $wrap.css('top', top + 'px'); } } else { // 向下滚动 if (top >= 0) { // 向下滚动到最底部,停止5s后向上滚动 _this.t && clearInterval(_this.t); _this.t = ''; _this.o = setTimeout(function() { _this.d = 1; _scroll(_this); }, 2000); } else { // 继续向下滚动 top = top + 1; $wrap.css('top', top + 'px'); } } }, 30); }; /** * 绑定hover事件 * @param {[type]} params [description] * @return [description] */ var _bindHover = function(_this) { _this.$wrap.hover(function(e) { _moveIn(_this); }, function(e) { _moveOut(_this); }); }; /** * 鼠标移入时间轴-暂停 * @param {[type]} params [description] * @return [description] */ var _moveIn = function(_this) { _this.t && clearInterval(_this.t); _this.t = ''; _this.o && clearTimeout(_this.o); _this.o = ''; }; /** * 方法实现说明 * @param {[type]} params [description] * @return [description] */ var _moveOut = function(_this) { _this.t && clearInterval(_this.t); _this.t = ''; _this.o && clearTimeout(_this.o); _this.o = ''; _scroll(_this); }; return timeScrollFun; })();
使用
var timeScroll = new TimeScroll().init({id: 'wrap'}); timeScroll.scrollList();