デモ:http://codepen.io/mo4_9/pen/qRyoKE
スライダーのセレクタ、初期値、最大値、最小値を渡せば、いくつでも量産できるようにする。
あとはinputのchangeを監視して、cookieなどに数値を保管すれば実用的。
class Slider {
// slider max min initialValue
constructor(opts={}) {
this.isDragging = false;
this.$slider = opts.$slider || $(".slider") || $("div");
this.$sliderInner = this.$slider.find(".slider__inner") || $("div");
this.$sliderFg = this.$slider.find(".slider__inner--fg") || $("div");
this.$sliderInput = this.$slider.find(".slider__input") || $("div");
this.initialValue = isNaN(opts.initialValue) ? 0 : opts.initialValue;
this.max = isNaN(opts.max) ? 1000 : opts.max;
this.min = isNaN(opts.min) ? 0 : opts.min;
this.isInt = opts.isInt || true;
this.floatNum = isNaN(opts.floatNum) ? 0 : opts.floatNum;
this.init();
this.initListener();
}
init() {
this.$sliderInput.val( this.initialValue );
// 初期のwidthを合わせる
this.fixSliderWidthByInputNum( this.initialValue );
}
initListener() {
const that = this;
// slider側
this.$sliderInner.on("mousedown", (e) => {
e.preventDefault();
this.isDragging = true;
})
this.$sliderInner.on("mouseup mouseleave", (e) => {
e.preventDefault();
this.isDragging = false;
})
this.$sliderInner.on("mousemove", (e) => {
e.preventDefault();
if(!this.isDragging) return;
let percent = ( (e.offsetX + 1) / this.$sliderInner.width() ) * 100;
percent = Math.min(percent, 100);
this.$sliderFg.css("width", `${percent}%`)
const num = this.getAdjustedNumber(percent);
this.$sliderInput.val( num ).change(); // changeイベント発火 http://qiita.com/foo9/items/51ffdaa5305fbc4efa58
})
// input側
this.$sliderInput.on("change", function(){
that.fixSliderWidthByInputNum( $(this).val() );
})
}
// inputの数値からスライダーのwidthを決定
fixSliderWidthByInputNum(num) {
let percent = ( num - this.min ) / ( this.max - this.min ) * 100;
percent = Math.min(percent, 100);
this.$sliderFg.css("width", `${percent}%`);
}
getAdjustedNumber(percent) {
let num = ( this.max - this.min ) * ( percent / 100 ) + this.min;
if (this.isInt) {
num = Math.floor(num);
} else {
num = num.toFixed(this.floatNum);
}
return num;
}
}
(() => {
new Slider({
$slider: $(".slider-01"),
initialValue: 50, max: 100, min: 30
})
new Slider({
$slider: $(".slider-02"),
initialValue: 1000, max: 5000, min: 300
})
new Slider({
$slider: $(".slider-03"),
initialValue: 2000, max: 10000, min: 1000
})
})()