js 代码
/** * created by hechao on 2017/6/25. */(function(){/**添加window对象hscoll属性*/window.hscoll = { buildscoll:function(el,options){ app.init(el,options); } }var app = {/**初始化组件*/init:function(el,option){ app.options = option; app.prevy = 0; app.el = document.getelementbyid(el); app.scoll = this.el.children[0]; app.h = this.el.offsetheight;//滑动范围高度app.ch = this.el.scrollheight;//内容的高度if(parsefloat(this.h)<=parsefloat(this.ch)){ app.sdiv = document.createelement('div'); app.scollb = document.createelement('div'); app.sdiv.setattribute('class','scrollbars'); app.scollb.setattribute('class','scollb'); app.scollb.style.height = parsefloat(this.h)*parsefloat(this.h)/parsefloat(this.ch) + 'px'; app.el.appendchild(this.sdiv); app.sdiv.appendchild(this.scollb); app.initevent(); } },/**绑定事件*/initevent:function (){ app.el.addeventlistener('touchstart', app.touchstart, false); app.el.addeventlistener('touchmove', app.touchmove, false); app.el.addeventlistener('touchend', app.touchend, false); },/**记录滑动初始位置*/touchstart:function(e){var point = app.getpoint(e); app.starty = point.pagey; },/**手指移动时,滚动条滚动*/touchmove:function(e){ e.preventdefault();//阻止默认行为var point = app.getpoint(e); app.movey = point.pagey; app.deltay = app.starty - app.movey;if((app.prevy - app.deltay)<=0 && (app.prevy - app.deltay)>= -(app.ch-app.h)){ app.domove(app.prevy - app.deltay); }if(app.options.interactivescrollbars){ app.domove2(app.prevy - app.deltay); }else{if((app.prevy - app.deltay)<=0 && (app.prevy - app.deltay)>= -(app.ch-app.h)){ app.domove2(app.prevy - app.deltay); } } },/**手指离开时,判断位置*/touchend:function(e){ app.prevy = app.prevy - app.deltay;if(app.prevy >= 0){ app.prevy = 0; app.domove(app.prevy,true); app.domove2(app.prevy,true); }if(app.prevy <= -(app.ch-app.h)){ app.prevy = -(app.ch-app.h); app.domove(app.prevy,true); app.domove2(app.prevy,true); } }, getpoint:function (e) {return e.touches ? e.touches[0] : e; },/**内容滑动*/domove:function (y,t){if(t){ app.scoll.setattribute('style', 'transform: translate(0px, '+y+'px);transition:transform 300ms ease'); }else{ app.scoll.setattribute('style', 'transform: translate(0px, '+y+'px);transition:transform 0ms ease'); } },/**滚动条滑动*/domove2:function(y,t){if(t){ app.scollb.setattribute('style', 'transform: translate(0px, '+-parsefloat(y)*parsefloat(app.h)/parsefloat(app.ch)+'px);transition:transform 0ms ease;height:'+parsefloat(app.h)*parsefloat(app.h)/parsefloat(app.ch) + 'px'+''); }else{ app.scollb.setattribute('style', 'transform: translate(0px, '+-parsefloat(y)*parsefloat(app.h)/parsefloat(app.ch)+'px);transition:transform 0ms ease;height:'+parsefloat(app.h)*parsefloat(app.h)/parsefloat(app.ch) + 'px'+''); } } } })();
以上就是js写一个简单的滚动条实例代码的详细内容。
