/** * 基于somesayss.js的模拟滚动条; * 只有滚动块和鼠标滚轮的功能; */ ;(function($){ var scrollbar = function(block, content){ return this instanceof scrollbar ? this.init(block, content) : new scrollbar(block, content); } scrollbar.prototype = { init: function(block, content){ this.bind(block, content); }, bind: function(block, content){ var self =this, block = self.block = $(block), content = $(content); //代码防御; if(!content.length || !block.length) return this; var contentbox = self.contentbox = content.parent(), blockbox = block.parent(), heightcont = content.height(), heightcontbox = contentbox.height(), heightblock = block.height(), heightblockbox = blockbox.height(), maxtopblock = heightblockbox - heightblock, maxtopcontent = heightcontbox - heightcont; //如果 if(maxtopcontent >= 0){ blockbox.hide(); return this; } self.bindblock(block, content, maxtopblock, maxtopcontent); self.bindmousewheel(contentbox, block, content, maxtopblock, maxtopcontent); return this; }, bindblock: function(block, content, maxtopblock, maxtopcontent){ var self = this, event = $.event, data = $.data, pointerynew = block.offset().top; var docmu = self.docmu = function(e){ event.unbind(document, 'mousemove'); document.onselectstart = function(){ return true; } } data(document, 'docmu', docmu); //绑定滑块鼠标按下事件 event(block[0], 'mousedown', function(e){ //阻止鼠标按下的时候会全选文字 document.onselectstart = function(){ return false; } e.stop(); //让滑块动起来!!! event(document, 'mousemove', function(e){ var pointeryold = e.pointery, guid = self.guid = pointeryold - pointerynew; //确立阀值最大,最小 guid < 0 && (guid = 0); guid > maxtopblock && (guid = maxtopblock); self.mainrun(block, content, guid, maxtopblock, maxtopcontent); }); }); //绑定滑块鼠标弹起事件 event(document, 'mouseup', docmu); }, bindmousewheel: function(contentbox, block, content, maxtopblock, maxtopcontent){ var self = this, event = $.event, guid = self.guid = 0; event(contentbox[0], 'mousewheel', function(e){ e.stop(); if(e.wheeldelta){ guid = self.guid += 30; guid > maxtopblock && (guid = self.guid = maxtopblock); self.mainrun(block, content, guid, maxtopblock, maxtopcontent); }else{ guid = self.guid -= 30; guid < 0 && (guid = self.guid = 0); self.mainrun(block, content, guid, maxtopblock, maxtopcontent); } }); }, mainrun: function(block, content, guid, maxtopblock, maxtopcontent){ block.css('top', guid+'px'); //通过滑块的百分比去设置内容层的top; var percent = guid/maxtopblock, needtop = maxtopcontent*percent; content.css('top', needtop+'px'); }, unbind: function(){ var self = this, event = $.event, data = $.data; event.unbind(self.block[0], 'mousedown'); event.unbind(self.contentbox[0], 'mousewheel'); event.unbind(document, 'mouseup', self.docmu); } } 'bind bindblock unbind bindmousewheel mainrun'.replace(/\w+/g,function(n){ scrollbar[n] = scrollbar.prototype[n] }) //全局调用 window.scrollbar = scrollbar; scrollbar('#scrollblock', '#scrollcontent'); })(somesayss);