真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

原生JS如何實(shí)現(xiàn)封裝拖動(dòng)驗(yàn)證滑塊

小編這次要給大家分享的是原生JS如何實(shí)現(xiàn)封裝拖動(dòng)驗(yàn)證滑塊,文章內(nèi)容豐富,感興趣的小伙伴可以來(lái)了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。

創(chuàng)新互聯(lián)長(zhǎng)期為上千客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對(duì)不同對(duì)象提供差異化的產(chǎn)品和服務(wù);打造開(kāi)放共贏平臺(tái),與合作伙伴共同營(yíng)造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為昌圖企業(yè)提供專(zhuān)業(yè)的成都網(wǎng)站設(shè)計(jì)、網(wǎng)站制作,昌圖網(wǎng)站改版等技術(shù)服務(wù)。擁有十年豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開(kāi)發(fā)。

前言

星期六閑著沒(méi)事,就想著寫(xiě)寫(xiě)原生js玩玩,在網(wǎng)上看了幾個(gè)效果后決定做這個(gè)效果,并且使用了prototype和eventEmitter封裝成了庫(kù)。

最終效果

原生JS如何實(shí)現(xiàn)封裝拖動(dòng)驗(yàn)證滑塊 

分析

看到這個(gè)效果我們首先應(yīng)該想到和拖動(dòng)有關(guān)的api: onmousedown, onmousemove, onmouseup

其次要支持用戶傳入放置這個(gè)組件的dom元素和完成的回調(diào)事件。

最終如何使用?

我們先來(lái)看下使用方式,再來(lái)決定我們?cè)趺淳帉?xiě)這個(gè)庫(kù)

原生JS如何實(shí)現(xiàn)封裝拖動(dòng)驗(yàn)證滑塊

具體使用就是這樣的,我們還想用戶能通過(guò)import等方式使用,所以我們就要支持esMoudule的導(dǎo)入方式。

編寫(xiě)庫(kù)的整體初始框架

(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'), //創(chuàng)建一個(gè)style元素
    head = document.head || document.getElementsByTagName('head')[0]; //獲取head元素
   style.type = 'text/css'; //這里必須顯示設(shè)置style元素的type屬性為text/css,否則在ie中不起作用
   if (style.styleSheet) { //IE
    var func = function () {
     try { //防止IE中stylesheet數(shù)量超過(guò)限制而發(fā)生錯(cuò)誤
      style.styleSheet.cssText = cssText;
     } catch (e) {

     }
    }
    //如果當(dāng)前styleSheet還不能用,則放到異步中則行
    if (style.styleSheet.disabled) {
     setTimeout(func, 10);
    } else {
     func();
    }
   } else { //w3c
    //w3c瀏覽器中只要?jiǎng)?chuàng)建文本節(jié)點(diǎn)插入到style元素中就行了
    var textNode = document.createTextNode(cssText);
    style.appendChild(textNode);
   }
   head.appendChild(style); //把創(chuàng)建的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';
  // 不重復(fù)添加事件
  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;//是否拖動(dòng)到最右側(cè)
 }

 SliderTools.defaultOptions = {
  el: document.body //默認(rèn)放到body里
 };
 
 var proto = SliderTools.prototype = new EventEmitter();//SliderTools繼承emitter
 
 proto.constructor = SliderTools;//修正構(gòu)造器

 proto.init = function () {
  this.createSlider();//創(chuàng)建插件所需要的dom元素
  this.getElements();//獲取創(chuàng)建好的元素
 }
 
 // =================代碼塊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是在判斷是在瀏覽器環(huán)境還是nodeJS環(huán)境,方便代碼三后期使用, 代碼塊2聲明了一個(gè)對(duì)象 SliderTools ,將用戶傳進(jìn)來(lái)的 option 和默認(rèn)的 defaultOption 進(jìn)行合并

編寫(xiě)核心函數(shù)1(創(chuàng)建dom和css)

proto.createSlider = function () {
 this.options.el.innerHTML = '
拖動(dòng)滑塊驗(yàn)證
';//像指定元素中放置插件的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/IiBpZD0iVzVNME1wQ2VoaUh7cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDIxIDc5LjE1NTc3MiwgMjAxNC8wMS8xMy0xOTo0NDowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDo0ZDhlNWY5My05NmI0LTRlNWQtOGFjYi03ZTY4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Dp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+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;}')//像頁(yè)面里add新的樣式 } proto.getElements = function () { this.slider = document.querySelector('#slider'); this.drag_bg = document.querySelector('.drag_bg'); this.handler = document.querySelector('.handler'); }

編寫(xiě)核心函數(shù)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) { //拖動(dòng)到了最右側(cè)
    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') //拖動(dòng)完成后的樣式
    util.addClass(self.handler, 'handler_ok_bg')////拖動(dòng)完成后的樣式
    self.handler.onmousedown = null //防止拖動(dòng)完成后再次拖動(dòng)
    self.emit('complete')//emit通知使用者的回調(diào)事件
   } else {
    util.setInlineStyle([self.handler], 'left', 0 + 'px');
    util.setInlineStyle([self.drag_bg], 'width', 0 + 'px');
   }
   document.onmousemove = null;
   document.onmouseup = null;
  }
 }
}

添加工具方法(核心函數(shù)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;
  }
 },
}

最終完整可運(yùn)行代碼

(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'), //創(chuàng)建一個(gè)style元素
    head = document.head || document.getElementsByTagName('head')[0]; //獲取head元素
   style.type = 'text/css'; //這里必須顯示設(shè)置style元素的type屬性為text/css,否則在ie中不起作用
   if (style.styleSheet) { //IE
    var func = function () {
     try { //防止IE中stylesheet數(shù)量超過(guò)限制而發(fā)生錯(cuò)誤
      style.styleSheet.cssText = cssText;
     } catch (e) {

     }
    }
    //如果當(dāng)前styleSheet還不能用,則放到異步中則行
    if (style.styleSheet.disabled) {
     setTimeout(func, 10);
    } else {
     func();
    }
   } else { //w3c
    //w3c瀏覽器中只要?jiǎng)?chuàng)建文本節(jié)點(diǎn)插入到style元素中就行了
    var textNode = document.createTextNode(cssText);
    style.appendChild(textNode);
   }
   head.appendChild(style); //把創(chuàng)建的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';

  // 不重復(fù)添加事件
  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 = '
拖動(dòng)滑塊驗(yàn)證
'; 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/IiBpZD0iVzVNME1wQ2VoaUh7cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDIxIDc5LjE1NTc3MiwgMjAxNC8wMS8xMy0xOTo0NDowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zO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5zdGFuY2VJRD0ieG1wLmlpZDphNWEzMWNhMC1hYmViLTQxNWEtYTEwZS04Y2U5NzRlN2Q4YTEiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6NGQ4ZTVmOTMtOTZiNC00ZTVkLThhY2ItN2U2ODhmMjE1NmU2Ii8+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('驗(yàn)證完成'); })

看完這篇關(guān)于原生JS如何實(shí)現(xiàn)封裝拖動(dòng)驗(yàn)證滑塊的文章,如果覺(jué)得文章內(nèi)容寫(xiě)得不錯(cuò)的話,可以把它分享出去給更多人看到。


網(wǎng)站標(biāo)題:原生JS如何實(shí)現(xiàn)封裝拖動(dòng)驗(yàn)證滑塊
地址分享:http://weahome.cn/article/ijpesi.html

其他資訊

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部