欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

原生JS封装拖动验证滑块的实现代码示例

程序员文章站 2022-04-09 16:15:33
前言星期六闲着没事,就想着写写原生js玩玩,在网上看了几个效果后决定做这个效果,并且使用了prototype和eventemitter封装成了库。最终效果 分析看到这个效果我们首先应该想到和拖动有关的...

前言

星期六闲着没事,就想着写写原生js玩玩,在网上看了几个效果后决定做这个效果,并且使用了prototype和eventemitter封装成了库。

最终效果

原生JS封装拖动验证滑块的实现代码示例 

分析

看到这个效果我们首先应该想到和拖动有关的api: onmousedown, onmousemove, onmouseup

其次要支持用户传入放置这个组件的dom元素和完成的回调事件。

最终如何使用?

我们先来看下使用方式,再来决定我们怎么编写这个库

原生JS封装拖动验证滑块的实现代码示例

具体使用就是这样的,我们还想用户能通过import等方式使用,所以我们就要支持esmoudule的导入方式。

编写库的整体初始框架

(function () {
 // =================代码块1=========================================
 var root = (typeof self == 'object' && self.self == self && self) ||
  (typeof global == 'object' && global.global == global && global) ||
  this || {}; 
 var util = {
  extend: function (target) {
   for (var i = 1, len = arguments.length; i < len; i++) {
    for (var prop in arguments[i]) {
     if (arguments[i].hasownproperty(prop)) {
      target[prop] = arguments[i][prop]
     }
    }
   }
   return target
  },
  isvalidlistener: function (listener) {
   if (typeof listener === 'function') {
    return true
   } else if (listener && typeof listener === 'object') {
    return util.isvalidlistener(listener.listener)
   } else {
    return false
   }
  },
  addcss: function (csstext) {
   var style = document.createelement('style'), //创建一个style元素
    head = document.head || document.getelementsbytagname('head')[0]; //获取head元素
   style.type = 'text/css'; //这里必须显示设置style元素的type属性为text/css,否则在ie中不起作用
   if (style.stylesheet) { //ie
    var func = function () {
     try { //防止ie中stylesheet数量超过限制而发生错误
      style.stylesheet.csstext = csstext;
     } catch (e) {

     }
    }
    //如果当前stylesheet还不能用,则放到异步中则行
    if (style.stylesheet.disabled) {
     settimeout(func, 10);
    } else {
     func();
    }
   } else { //w3c
    //w3c浏览器中只要创建文本节点插入到style元素中就行了
    var textnode = document.createtextnode(csstext);
    style.appendchild(textnode);
   }
   head.appendchild(style); //把创建的style元素插入到head中
  },
  indexof: function (array, item) {
   if (array.indexof) {
    return array.indexof(item);
   } else {
    var result = -1;
    for (var i = 0, len = array.length; i < len; i++) {
     if (array[i] === item) {
      result = i;
      break;
     }
    }
    return result;
   }
  }
 }
 
 function eventemitter() {
  this._events = {}
 }

 eventemitter.prototype.on = function (eventname, listener) {
  if (!eventname || !listener) return;
  if (!util.isvalidlistener(listener)) {
   throw new typeerror('listener must be a function');
  }
  var events = this._events;
  var listeners = events[eventname] = events[eventname] || [];
  var listeneriswrapped = typeof listener === 'object';
  // 不重复添加事件
  if (util.indexof(listeners, listener) === -1) {
   listeners.push(listeneriswrapped ? listener : {
    listener: listener,
    once: false
   });
  }
  return this;
 };
 eventemitter.prototype.once = function (eventname, listener) {
  return this.on(eventname, {
   listener: listener,
   once: true
  })
 };
 eventemitter.prototype.off = function (eventname, listener) {
  var listeners = this._events[eventname];
  if (!listeners) return;
  var index;
  for (var i = 0, len = listeners.length; i < len; i++) {
   if (listeners[i] && listeners[i].listener === listener) {
    index = i;
    break;
   }
  }
  if (typeof index !== 'undefined') {
   listeners.splice(index, 1, null)
  }
  return this;
 };
 eventemitter.prototype.emit = function (eventname, args) {
  var listeners = this._events[eventname];
  if (!listeners) return;
  for (var i = 0; i < listeners.length; i++) {
   var listener = listeners[i];
   if (listener) {
    listener.listener.apply(this, args || []);
    if (listener.once) {
     this.off(eventname, listener.listener)
    }
   }
  }
  return this;
 };
 
 // =================代码块2=========================================
 function slidertools(options) {
  this.options = util.extend({}, this.constructor.defaultoptions, options)
  this.init();
  this.bindevents();
  this.diffx = 0;
  this.flag = false;//是否拖动到最右侧
 }

 slidertools.defaultoptions = {
  el: document.body //默认放到body里
 };
 
 var proto = slidertools.prototype = new eventemitter();//slidertools继承emitter
 
 proto.constructor = slidertools;//修正构造器

 proto.init = function () {
  this.createslider();//创建插件所需要的dom元素
  this.getelements();//获取创建好的元素
 }
 
 // =================代码块3=========================================
 if (typeof exports != 'undefined' && !exports.nodetype) {
  if (typeof module != 'undefined' && !module.nodetype && module.exports) {
   exports = module.exports = slidertools;
  }
  exports.slidertools = slidertools;
 } else {
  root.slidertools = slidertools;
 }
}());

代码块1是在判断是在浏览器环境还是nodejs环境,方便代码三后期使用, 代码块2声明了一个对象 slidertools ,将用户传进来的 option 和默认的 defaultoption 进行合并

编写核心函数1(创建dom和css)

proto.createslider = function () {
 this.options.el.innerhtml = '<div id="slider"><div class="drag_bg"></div><div class="drag_text" onselectstart="return false;" unselectable="on">拖动滑块验证</div><div class="handler handler_bg"></div></div>';//像指定元素中放置插件的dom元素
 util.addcss('ul,li {list-style: none;} a {text-decoration: none;} .wrap {width: 300px;height: 350px;text-align: center;margin: 150px auto;}.inner {padding: 15px;} .clearfix {overflow: hidden;_zoom: 1;} .none {display: none;} #slider {position:relative;background-color: #e8e8e8;width: 300px;height: 34px;line-height: 34px;text-align: center;} #slider .handler {position: absolute;top: 0px;left: 0px;width: 40px;height: 32px;border: 1px solid #ccc;cursor: move;} .handler_bg {background: #fff url("data:image/png;base64,ivborw0kggoaaaansuheugaaabaaaaaqcayaaaaf8/9haaaagxrfwhrtb2z0d2fyzqbbzg9izsbjbwfnzvjlywr5ccllpaaaa3hpvfh0we1momnvbs5hzg9izs54bxaaaaaaadw/ehbhy2tldcbizwdpbj0i77u/iibpzd0ivzvnme1wq2voauh6cmvtek5uy3pryzlkij8+idx4onhtcg1ldgegeg1sbnm6ed0iywrvymu6bnm6bwv0ys8iihg6eg1wdgs9ikfkb2jlifhnucbdb3jliduuns1jmdixidc5lje1ntc3miwgmjaxnc8wms8xmy0xoto0ndowmcagicagicagij4gphjkzjpsreygeg1sbnm6cmrmpsjodhrwoi8vd3d3lnczlm9yzy8xotk5lzaylziylxjkzi1zew50yxgtbnmjij4gphjkzjpezxnjcmlwdglvbibyzgy6ywjvdxq9iiigeg1sbnm6eg1wtu09imh0dha6ly9ucy5hzg9izs5jb20vegfwlzeumc9tbs8iihhtbg5zonn0umvmpsjodhrwoi8vbnmuywrvymuuy29tl3hhcc8xljavc1r5cguvumvzb3vyy2vszwyjiib4bwxuczp4bxa9imh0dha6ly9ucy5hzg9izs5jb20vegfwlzeumc8iihhtce1nok9yawdpbmfsrg9jdw1lbnrjrd0ieg1wlmrpzdo0zdhlnwy5my05nmi0ltrlnwqtogfjyi03zty4ogyymtu2ztyiihhtce1nokrvy3vtzw50suq9inhtcc5kawq6nteyntvemurgmkvfmtffnei5ndbcmjq2m0exmdq1ouyiihhtce1nokluc3rhbmnlsuq9inhtcc5pawq6nteyntvemungmkvfmtffnei5ndbcmjq2m0exmdq1ouyiihhtcdpdcmvhdg9yvg9vbd0iqwrvymugughvdg9zag9wiendidiwmtqgke1hy2ludg9zackipia8eg1wtu06rgvyaxzlzezyb20gc3rszwy6aw5zdgfuy2vjrd0ieg1wlmlpzdo2mtc5nznmzs02otqxltqyotytytiwni02ndi2ytnkowu5ymuiihn0umvmomrvy3vtzw50suq9inhtcc5kawq6ngq4ztvmotmtotzinc00ztvklthhy2itn2u2odhmmje1nmu2ii8+idwvcmrmokrlc2nyaxb0aw9upia8l3jkzjpsrey+idwvedp4bxbtzxrhpia8p3hwywnrzxqgzw5kpsjyij8+yirg4aaaalfjrefuenpi/p//pwmlgimbqka9a+bonfsiiboxkcinh+ycacdubyoswaiopxwjciacfegbqz1avbsis5otk/8tkmnejwwgqiugtquijwaxuf3yx3xygieiflwhpkyawb+i1xgswxuligf9a7mqkbwtlhbxaflhgpgqeactkmncu6al9d8wii4hovk3itkwjaxwumloogqhmse45viq2kubuasoyc4wf+ouyxz6mqkgwaan9mirurecxgaaaabjru5erkjggg==") no-repeat center;} .handler_ok_bg {background: #fff url("data:image/png;base64,ivborw0kggoaaaansuheugaaabaaaaaqcayaaaaf8/9haaaagxrfwhrtb2z0d2fyzqbbzg9izsbjbwfnzvjlywr5ccllpaaaa3hpvfh0we1momnvbs5hzg9izs54bxaaaaaaadw/ehbhy2tldcbizwdpbj0i77u/iibpzd0ivzvnme1wq2voauh6cmvtek5uy3pryzlkij8+idx4onhtcg1ldgegeg1sbnm6ed0iywrvymu6bnm6bwv0ys8iihg6eg1wdgs9ikfkb2jlifhnucbdb3jliduuns1jmdixidc5lje1ntc3miwgmjaxnc8wms8xmy0xoto0ndowmcagicagicagij4gphjkzjpsreygeg1sbnm6cmrmpsjodhrwoi8vd3d3lnczlm9yzy8xotk5lzaylziylxjkzi1zew50yxgtbnmjij4gphjkzjpezxnjcmlwdglvbibyzgy6ywjvdxq9iiigeg1sbnm6eg1wtu09imh0dha6ly9ucy5hzg9izs5jb20vegfwlzeumc9tbs8iihhtbg5zonn0umvmpsjodhrwoi8vbnmuywrvymuuy29tl3hhcc8xljavc1r5cguvumvzb3vyy2vszwyjiib4bwxuczp4bxa9imh0dha6ly9ucy5hzg9izs5jb20vegfwlzeumc8iihhtce1nok9yawdpbmfsrg9jdw1lbnrjrd0ieg1wlmrpzdo0zdhlnwy5my05nmi0ltrlnwqtogfjyi03zty4ogyymtu2ztyiihhtce1nokrvy3vtzw50suq9inhtcc5kawq6ndlbrdi3njvgmkq2mtffnei5ndbcmjq2m0exmdq1ouyiihhtce1nokluc3rhbmnlsuq9inhtcc5pawq6ndlbrdi3njrgmkq2mtffnei5ndbcmjq2m0exmdq1ouyiihhtcdpdcmvhdg9yvg9vbd0iqwrvymugughvdg9zag9wiendidiwmtqgke1hy2ludg9zackipia8eg1wtu06rgvyaxzlzezyb20gc3rszwy6aw5zdgfuy2vjrd0ieg1wlmlpzdphnwezmwnhmc1hymviltqxnwetytewzs04y2u5nzrln2q4yteiihn0umvmomrvy3vtzw50suq9inhtcc5kawq6ngq4ztvmotmtotzinc00ztvklthhy2itn2u2odhmmje1nmu2ii8+idwvcmrmokrlc2nyaxb0aw9upia8l3jkzjpsrey+idwvedp4bxbtzxrhpia8p3hwywnrzxqgzw5kpsjyij8+k+shwwaaaszjrefuenpi/p//pwmykd8uzw+kuodyeyglomivghg/em/pthx0efk9i8waoez+idupiimy8in1qjwenogj3aco5gnabmbahlgaxa4gq5igannj0mwavtsx7ikyy7l2unujaf+amamj78aedtbiwgyg5gbifcsxfczoabmcy4a4gojnh0d6dpk4ixnsvihafsdoaelrajrjgjp/awpbhmhejiqnwyrmuznq4vqgdqqxk0ia/0i17wjipmqntnbeagmlqiwiqa2vgww7qppbekgxsajiieusbnnsbdweay9mefgmmgbk00e0izta7ahectdq58mrua6wllggfmompig1qfegwaixgzo8guhiysmwqgsazgwhaezhicizoabkjkqym0caaqdgx279jf50aaaaaabjru5erkjggg==") no-repeat center;}#slider .drag_bg {background-color: #7ac23c; height: 34px;width: 0px;} #slider .drag_text {position: absolute; top: 0px;width: 300px;-moz-user-select: none;-webkit-user-select: none;user-select: none;-o-user-select: none;-ms-user-select: none; }.unselect {-moz-user-select: none;-webkit-user-select: none; -ms-user-select: none;}.slide_ok {color: #fff;}')//像页面里add新的样式
}
proto.getelements = function () {
 this.slider = document.queryselector('#slider');
 this.drag_bg = document.queryselector('.drag_bg');
 this.handler = document.queryselector('.handler');
}

编写核心函数2(绑定事件)

proto.bindevents = function () {
 var self = this;
 self.handler.onmousedown = function (e) {
  self.diffx = e.clientx - self.handler.offsetleft;
  util.setclassname(self.slider, 'unselect'); //禁止选择样式
  document.onmousemove = function (e) {
   let deltax = e.clientx - self.diffx;
   if (deltax >= self.slider.offsetwidth - self.handler.offsetwidth) { //拖动到了最右侧
    deltax = self.slider.offsetwidth - self.handler.offsetwidth;
    self.flag = true;
   } else if (deltax <= 0) {
    deltax = 0;
    self.flag = false;
   } else {
    self.flag = false;
   }
   util.setinlinestyle([self.handler], 'left', deltax + 'px');
   util.setinlinestyle([self.drag_bg], 'width', deltax + 'px');
  }
  document.onmouseup = function (e) {
   util.setclassname(self.slider, '')
   if (self.flag) {
    util.setclassname(self.slider, 'slide_ok') //拖动完成后的样式
    util.addclass(self.handler, 'handler_ok_bg')////拖动完成后的样式
    self.handler.onmousedown = null //防止拖动完成后再次拖动
    self.emit('complete')//emit通知使用者的回调事件
   } else {
    util.setinlinestyle([self.handler], 'left', 0 + 'px');
    util.setinlinestyle([self.drag_bg], 'width', 0 + 'px');
   }
   document.onmousemove = null;
   document.onmouseup = null;
  }
 }
}

添加工具方法(核心函数2中用到的)

var util = {
 // ...初始框架里的那部分
 setclassname(selector, classname) {
  selector.classname = classname;
 },
 addclass(selector, classname) {
  selector.classlist.add(classname);
 },
 setinlinestyle(selector, attr, content) {
  let length = selector.length;
  for (let i = 0; i < length; i++) {
   selector[i].style[attr] = content;
  }
 },
}

最终完整可运行代码

(function () {
 var root = (typeof self == 'object' && self.self == self && self) ||
  (typeof global == 'object' && global.global == global && global) ||
  this || {};
 var util = {
  extend: function (target) {
   for (var i = 1, len = arguments.length; i < len; i++) {
    for (var prop in arguments[i]) {
     if (arguments[i].hasownproperty(prop)) {
      target[prop] = arguments[i][prop]
     }
    }
   }
   return target
  },
  setclassname(selector, classname) {
   selector.classname = classname;
  },
  addclass(selector, classname) {
   selector.classlist.add(classname);
  },
  setinlinestyle(selector, attr, content) {
   let length = selector.length;
   for (let i = 0; i < length; i++) {
    selector[i].style[attr] = content;
   }
  },
  isvalidlistener: function (listener) {
   if (typeof listener === 'function') {
    return true
   } else if (listener && typeof listener === 'object') {
    return util.isvalidlistener(listener.listener)
   } else {
    return false
   }
  },
  addcss: function (csstext) {
   var style = document.createelement('style'), //创建一个style元素
    head = document.head || document.getelementsbytagname('head')[0]; //获取head元素
   style.type = 'text/css'; //这里必须显示设置style元素的type属性为text/css,否则在ie中不起作用
   if (style.stylesheet) { //ie
    var func = function () {
     try { //防止ie中stylesheet数量超过限制而发生错误
      style.stylesheet.csstext = csstext;
     } catch (e) {

     }
    }
    //如果当前stylesheet还不能用,则放到异步中则行
    if (style.stylesheet.disabled) {
     settimeout(func, 10);
    } else {
     func();
    }
   } else { //w3c
    //w3c浏览器中只要创建文本节点插入到style元素中就行了
    var textnode = document.createtextnode(csstext);
    style.appendchild(textnode);
   }
   head.appendchild(style); //把创建的style元素插入到head中
  },
  indexof: function (array, item) {
   if (array.indexof) {
    return array.indexof(item);
   } else {
    var result = -1;
    for (var i = 0, len = array.length; i < len; i++) {
     if (array[i] === item) {
      result = i;
      break;
     }
    }
    return result;
   }
  }
 }

 function eventemitter() {
  this._events = {}
 }

 eventemitter.prototype.on = function (eventname, listener) {
  if (!eventname || !listener) return;

  if (!util.isvalidlistener(listener)) {
   throw new typeerror('listener must be a function');
  }

  var events = this._events;
  var listeners = events[eventname] = events[eventname] || [];
  var listeneriswrapped = typeof listener === 'object';

  // 不重复添加事件
  if (util.indexof(listeners, listener) === -1) {
   listeners.push(listeneriswrapped ? listener : {
    listener: listener,
    once: false
   });
  }

  return this;
 };
 eventemitter.prototype.once = function (eventname, listener) {
  return this.on(eventname, {
   listener: listener,
   once: true
  })
 };
 eventemitter.prototype.off = function (eventname, listener) {
  var listeners = this._events[eventname];
  if (!listeners) return;

  var index;
  for (var i = 0, len = listeners.length; i < len; i++) {
   if (listeners[i] && listeners[i].listener === listener) {
    index = i;
    break;
   }
  }

  if (typeof index !== 'undefined') {
   listeners.splice(index, 1, null)
  }

  return this;
 };
 eventemitter.prototype.emit = function (eventname, args) {
  var listeners = this._events[eventname];
  if (!listeners) return;

  for (var i = 0; i < listeners.length; i++) {
   var listener = listeners[i];
   if (listener) {
    listener.listener.apply(this, args || []);
    if (listener.once) {
     this.off(eventname, listener.listener)
    }
   }
  }
  return this;
 };

 function slidertools(options) {
  this.options = util.extend({}, this.constructor.defaultoptions, options)
  this.init();
  this.bindevents();
  this.diffx = 0;
  this.flag = false;
 }

 slidertools.version = '1.0.0';

 slidertools.defaultoptions = {
  el: document.body
 };

 var proto = slidertools.prototype = new eventemitter();

 proto.constructor = slidertools;

 proto.init = function () {
  this.createslider();
  this.getelements();
 }

 proto.createslider = function () {
  this.options.el.innerhtml = '<div id="slider"><div class="drag_bg"></div><div class="drag_text" onselectstart="return false;" unselectable="on">拖动滑块验证</div><div class="handler handler_bg"></div></div>';
  util.addcss('ul, li { list-style: none; } a { text-decoration: none; } .wrap { width: 300px; height: 350px; text-align: center; margin: 150px auto; } .inner { padding: 15px; } .clearfix { overflow: hidden; _zoom: 1; } .none { display: none; } #slider { position: relative; background-color: #e8e8e8; width: 300px; height: 34px; line-height: 34px; text-align: center; } #slider .handler { position: absolute; top: 0px; left: 0px; width: 40px; height: 32px; border: 1px solid #ccc; cursor: move;} .handler_bg { background: #fff url("data:image/png;base64,ivborw0kggoaaaansuheugaaabaaaaaqcayaaaaf8/9haaaagxrfwhrtb2z0d2fyzqbbzg9izsbjbwfnzvjlywr5ccllpaaaa3hpvfh0we1momnvbs5hzg9izs54bxaaaaaaadw/ehbhy2tldcbizwdpbj0i77u/iibpzd0ivzvnme1wq2voauh6cmvtek5uy3pryzlkij8+idx4onhtcg1ldgegeg1sbnm6ed0iywrvymu6bnm6bwv0ys8iihg6eg1wdgs9ikfkb2jlifhnucbdb3jliduuns1jmdixidc5lje1ntc3miwgmjaxnc8wms8xmy0xoto0ndowmcagicagicagij4gphjkzjpsreygeg1sbnm6cmrmpsjodhrwoi8vd3d3lnczlm9yzy8xotk5lzaylziylxjkzi1zew50yxgtbnmjij4gphjkzjpezxnjcmlwdglvbibyzgy6ywjvdxq9iiigeg1sbnm6eg1wtu09imh0dha6ly9ucy5hzg9izs5jb20vegfwlzeumc9tbs8iihhtbg5zonn0umvmpsjodhrwoi8vbnmuywrvymuuy29tl3hhcc8xljavc1r5cguvumvzb3vyy2vszwyjiib4bwxuczp4bxa9imh0dha6ly9ucy5hzg9izs5jb20vegfwlzeumc8iihhtce1nok9yawdpbmfsrg9jdw1lbnrjrd0ieg1wlmrpzdo0zdhlnwy5my05nmi0ltrlnwqtogfjyi03zty4ogyymtu2ztyiihhtce1nokrvy3vtzw50suq9inhtcc5kawq6nteyntvemurgmkvfmtffnei5ndbcmjq2m0exmdq1ouyiihhtce1nokluc3rhbmnlsuq9inhtcc5pawq6nteyntvemungmkvfmtffnei5ndbcmjq2m0exmdq1ouyiihhtcdpdcmvhdg9yvg9vbd0iqwrvymugughvdg9zag9wiendidiwmtqgke1hy2ludg9zackipia8eg1wtu06rgvyaxzlzezyb20gc3rszwy6aw5zdgfuy2vjrd0ieg1wlmlpzdo2mtc5nznmzs02otqxltqyotytytiwni02ndi2ytnkowu5ymuiihn0umvmomrvy3vtzw50suq9inhtcc5kawq6ngq4ztvmotmtotzinc00ztvklthhy2itn2u2odhmmje1nmu2ii8+idwvcmrmokrlc2nyaxb0aw9upia8l3jkzjpsrey+idwvedp4bxbtzxrhpia8p3hwywnrzxqgzw5kpsjyij8+yirg4aaaalfjrefuenpi/p//pwmlgimbqka9a+bonfsiiboxkcinh+ycacdubyoswaiopxwjciacfegbqz1avbsis5otk/8tkmnejwwgqiugtquijwaxuf3yx3xygieiflwhpkyawb+i1xgswxuligf9a7mqkbwtlhbxaflhgpgqeactkmncu6al9d8wii4hovk3itkwjaxwumloogqhmse45viq2kubuasoyc4wf+ouyxz6mqkgwaan9mirurecxgaaaabjru5erkjggg==") no-repeat center; } .handler_ok_bg { background: #fff url("data:image/png;base64,ivborw0kggoaaaansuheugaaabaaaaaqcayaaaaf8/9haaaagxrfwhrtb2z0d2fyzqbbzg9izsbjbwfnzvjlywr5ccllpaaaa3hpvfh0we1momnvbs5hzg9izs54bxaaaaaaadw/ehbhy2tldcbizwdpbj0i77u/iibpzd0ivzvnme1wq2voauh6cmvtek5uy3pryzlkij8+idx4onhtcg1ldgegeg1sbnm6ed0iywrvymu6bnm6bwv0ys8iihg6eg1wdgs9ikfkb2jlifhnucbdb3jliduuns1jmdixidc5lje1ntc3miwgmjaxnc8wms8xmy0xoto0ndowmcagicagicagij4gphjkzjpsreygeg1sbnm6cmrmpsjodhrwoi8vd3d3lnczlm9yzy8xotk5lzaylziylxjkzi1zew50yxgtbnmjij4gphjkzjpezxnjcmlwdglvbibyzgy6ywjvdxq9iiigeg1sbnm6eg1wtu09imh0dha6ly9ucy5hzg9izs5jb20vegfwlzeumc9tbs8iihhtbg5zonn0umvmpsjodhrwoi8vbnmuywrvymuuy29tl3hhcc8xljavc1r5cguvumvzb3vyy2vszwyjiib4bwxuczp4bxa9imh0dha6ly9ucy5hzg9izs5jb20vegfwlzeumc8iihhtce1nok9yawdpbmfsrg9jdw1lbnrjrd0ieg1wlmrpzdo0zdhlnwy5my05nmi0ltrlnwqtogfjyi03zty4ogyymtu2ztyiihhtce1nokrvy3vtzw50suq9inhtcc5kawq6ndlbrdi3njvgmkq2mtffnei5ndbcmjq2m0exmdq1ouyiihhtce1nokluc3rhbmnlsuq9inhtcc5pawq6ndlbrdi3njrgmkq2mtffnei5ndbcmjq2m0exmdq1ouyiihhtcdpdcmvhdg9yvg9vbd0iqwrvymugughvdg9zag9wiendidiwmtqgke1hy2ludg9zackipia8eg1wtu06rgvyaxzlzezyb20gc3rszwy6aw5zdgfuy2vjrd0ieg1wlmlpzdphnwezmwnhmc1hymviltqxnwetytewzs04y2u5nzrln2q4yteiihn0umvmomrvy3vtzw50suq9inhtcc5kawq6ngq4ztvmotmtotzinc00ztvklthhy2itn2u2odhmmje1nmu2ii8+idwvcmrmokrlc2nyaxb0aw9upia8l3jkzjpsrey+idwvedp4bxbtzxrhpia8p3hwywnrzxqgzw5kpsjyij8+k+shwwaaaszjrefuenpi/p//pwmykd8uzw+kuodyeyglomivghg/em/pthx0efk9i8waoez+idupiimy8in1qjwenogj3aco5gnabmbahlgaxa4gq5igannj0mwavtsx7ikyy7l2unujaf+amamj78aedtbiwgyg5gbifcsxfczoabmcy4a4gojnh0d6dpk4ixnsvihafsdoaelrajrjgjp/awpbhmhejiqnwyrmuznq4vqgdqqxk0ia/0i17wjipmqntnbeagmlqiwiqa2vgww7qppbekgxsajiieusbnnsbdweay9mefgmmgbk00e0izta7ahectdq58mrua6wllggfmompig1qfegwaixgzo8guhiysmwqgsazgwhaezhicizoabkjkqym0caaqdgx279jf50aaaaaabjru5erkjggg==") no-repeat center; } #slider .drag_bg { background-color: #7ac23c; height: 34px; width: 0px;  } #slider .drag_text { position: absolute; top: 0px; width: 300px; -moz-user-select: none; -webkit-user-select: none; user-select: none; -o-user-select: none; -ms-user-select: none; } .unselect { -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; } .slide_ok { color: #fff; }')
 }
 proto.getelements = function () {
  this.slider = document.queryselector('#slider');
  this.drag_bg = document.queryselector('.drag_bg');
  this.handler = document.queryselector('.handler');
 }
 proto.bindevents = function () {
  var self = this;
  self.handler.onmousedown = function (e) {
   self.diffx = e.clientx - self.handler.offsetleft;
   util.setclassname(self.slider, 'unselect');
   document.onmousemove = function (e) {
    let deltax = e.clientx - self.diffx;
    if (deltax >= self.slider.offsetwidth - self.handler.offsetwidth) {
     deltax = self.slider.offsetwidth - self.handler.offsetwidth;
     self.flag = true;
    } else if (deltax <= 0) {
     deltax = 0;
     self.flag = false;
    } else {
     self.flag = false;
    }
    util.setinlinestyle([self.handler], 'left', deltax + 'px');
    util.setinlinestyle([self.drag_bg], 'width', deltax + 'px');
   }
   document.onmouseup = function (e) {
    util.setclassname(self.slider, '')
    if (self.flag) {
     util.setclassname(self.slider, 'slide_ok')
     util.addclass(self.handler, 'handler_ok_bg')
     self.handler.onmousedown = null
     self.emit('complete')
    } else {
     util.setinlinestyle([self.handler], 'left', 0 + 'px');
     util.setinlinestyle([self.drag_bg], 'width', 0 + 'px');
    }
    document.onmousemove = null;
    document.onmouseup = null;
   }
  }
 }
 if (typeof exports != 'undefined' && !exports.nodetype) {
  if (typeof module != 'undefined' && !module.nodetype && module.exports) {
   exports = module.exports = slidertools;
  }
  exports.slidertools = slidertools;
 } else {
  root.slidertools = slidertools;
 }
}());

let slider = new slidertools();
slider.on('complete',() => {
 alert('验证完成');
})

结语

参考资料

到此这篇关于原生js封装拖动验证滑块的实现代码示例的文章就介绍到这了,更多相关js 拖动验证滑块内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!