提交 1b4ce382 编写于 作者: A Abdullah Almsaeed

Merge pull request #118 from alexishida/master

update bootstrap-slide.js
...@@ -140,6 +140,9 @@ ...@@ -140,6 +140,9 @@
background: transparent none; background: transparent none;
} }
.slider-disabled .slider-selection {
opacity: 0.5;
}
#red .slider-selection { #red .slider-selection {
background: #f56954; background: #f56954;
......
/* ========================================================= /*! =========================================================
* bootstrap-slider.js v2.0.0 * bootstrap-slider.js
* http://www.eyecon.ro/bootstrap-slider *
* Maintainers:
* Kyle Kemp
* - Twitter: @seiyria
* - Github: seiyria
* Rohit Kalkur
* - Twitter: @Rovolutionary
* - Github: rovolution
*
* ========================================================= * =========================================================
* Copyright 2012 Stefan Petre
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
...@@ -16,373 +23,1145 @@ ...@@ -16,373 +23,1145 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
* ========================================================= */ * ========================================================= */
!function( $ ) {
var Slider = function(element, options) {
this.element = $(element);
this.picker = $('<div class="slider">'+
'<div class="slider-track">'+
'<div class="slider-selection"></div>'+
'<div class="slider-handle"></div>'+
'<div class="slider-handle"></div>'+
'</div>'+
'<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'+
'</div>')
.insertBefore(this.element)
.append(this.element);
this.id = this.element.data('slider-id')||options.id;
if (this.id) {
this.picker[0].id = this.id;
}
if (typeof Modernizr !== 'undefined' && Modernizr.touch) {
this.touchCapable = true;
}
var tooltip = this.element.data('slider-tooltip')||options.tooltip; /**
* Bridget makes jQuery widgets
* v1.0.1
* MIT license
*/
( function( $ ) {
this.tooltip = this.picker.find('.tooltip'); ( function( $ ) {
this.tooltipInner = this.tooltip.find('div.tooltip-inner');
this.orientation = this.element.data('slider-orientation')||options.orientation; 'use strict';
switch(this.orientation) {
case 'vertical':
this.picker.addClass('slider-vertical');
this.stylePos = 'top';
this.mousePos = 'pageY';
this.sizePos = 'offsetHeight';
this.tooltip.addClass('right')[0].style.left = '100%';
break;
default:
this.picker
.addClass('slider-horizontal')
.css('width', this.element.outerWidth());
this.orientation = 'horizontal';
this.stylePos = 'left';
this.mousePos = 'pageX';
this.sizePos = 'offsetWidth';
this.tooltip.addClass('top')[0].style.top = -this.tooltip.outerHeight() - 14 + 'px';
break;
}
this.min = this.element.data('slider-min')||options.min; // -------------------------- utils -------------------------- //
this.max = this.element.data('slider-max')||options.max;
this.step = this.element.data('slider-step')||options.step;
this.value = this.element.data('slider-value')||options.value;
if (this.value[1]) {
this.range = true;
}
this.selection = this.element.data('slider-selection')||options.selection; var slice = Array.prototype.slice;
this.selectionEl = this.picker.find('.slider-selection');
if (this.selection === 'none') {
this.selectionEl.addClass('hide');
}
this.selectionElStyle = this.selectionEl[0].style;
this.handle1 = this.picker.find('.slider-handle:first');
this.handle1Stype = this.handle1[0].style;
this.handle2 = this.picker.find('.slider-handle:last');
this.handle2Stype = this.handle2[0].style;
var handle = this.element.data('slider-handle')||options.handle;
switch(handle) {
case 'round':
this.handle1.addClass('round');
this.handle2.addClass('round');
break
case 'triangle':
this.handle1.addClass('triangle');
this.handle2.addClass('triangle');
break
}
if (this.range) { function noop() {}
this.value[0] = Math.max(this.min, Math.min(this.max, this.value[0]));
this.value[1] = Math.max(this.min, Math.min(this.max, this.value[1])); // -------------------------- definition -------------------------- //
} else {
this.value = [ Math.max(this.min, Math.min(this.max, this.value))]; function defineBridget( $ ) {
this.handle2.addClass('hide');
if (this.selection == 'after') { // bail if no jQuery
this.value[1] = this.max; if ( !$ ) {
} else { return;
this.value[1] = this.min;
} }
}
this.diff = this.max - this.min;
this.percentage = [
(this.value[0]-this.min)*100/this.diff,
(this.value[1]-this.min)*100/this.diff,
this.step*100/this.diff
];
this.offset = this.picker.offset(); // -------------------------- addOptionMethod -------------------------- //
this.size = this.picker[0][this.sizePos];
this.formater = options.formater; /**
* adds option method -> $().plugin('option', {...})
* @param {Function} PluginClass - constructor class
*/
function addOptionMethod( PluginClass ) {
// don't overwrite original option method
if ( PluginClass.prototype.option ) {
return;
}
this.layout(); // option setter
PluginClass.prototype.option = function( opts ) {
// bail out if not an object
if ( !$.isPlainObject( opts ) ){
return;
}
this.options = $.extend( true, this.options, opts );
};
}
if (this.touchCapable) {
// Touch: Bind touch events:
this.picker.on({
touchstart: $.proxy(this.mousedown, this)
});
} else {
this.picker.on({
mousedown: $.proxy(this.mousedown, this)
});
}
if (tooltip === 'show') { // -------------------------- plugin bridge -------------------------- //
this.picker.on({
mouseenter: $.proxy(this.showTooltip, this), // helper function for logging errors
mouseleave: $.proxy(this.hideTooltip, this) // $.error breaks jQuery chaining
}); var logError = typeof console === 'undefined' ? noop :
} else { function( message ) {
this.tooltip.addClass('hide'); console.error( message );
};
/**
* jQuery plugin bridge, access methods like $elem.plugin('method')
* @param {String} namespace - plugin name
* @param {Function} PluginClass - constructor class
*/
function bridge( namespace, PluginClass ) {
// add to jQuery fn namespace
$.fn[ namespace ] = function( options ) {
if ( typeof options === 'string' ) {
// call plugin method when first argument is a string
// get arguments for method
var args = slice.call( arguments, 1 );
for ( var i=0, len = this.length; i < len; i++ ) {
var elem = this[i];
var instance = $.data( elem, namespace );
if ( !instance ) {
logError( "cannot call methods on " + namespace + " prior to initialization; " +
"attempted to call '" + options + "'" );
continue;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === '_' ) {
logError( "no such method '" + options + "' for " + namespace + " instance" );
continue;
}
// trigger method with arguments
var returnValue = instance[ options ].apply( instance, args);
// break look and return first value if provided
if ( returnValue !== undefined && returnValue !== instance) {
return returnValue;
}
}
// return this if no return value
return this;
} else {
var objects = this.map( function() {
var instance = $.data( this, namespace );
if ( instance ) {
// apply options & init
instance.option( options );
instance._init();
} else {
// initialize new instance
instance = new PluginClass( this, options );
$.data( this, namespace, instance );
}
return $(this);
});
if(!objects || objects.length > 1) {
return objects;
} else {
return objects[0];
}
}
};
}
// -------------------------- bridget -------------------------- //
/**
* converts a Prototypical class into a proper jQuery plugin
* the class must have a ._init method
* @param {String} namespace - plugin name, used in $().pluginName
* @param {Function} PluginClass - constructor class
*/
$.bridget = function( namespace, PluginClass ) {
addOptionMethod( PluginClass );
bridge( namespace, PluginClass );
};
return $.bridget;
} }
};
// get jquery from browser global
Slider.prototype = { defineBridget( $ );
constructor: Slider,
})( $ );
over: false,
inDrag: false,
/*************************************************
showTooltip: function(){
this.tooltip.addClass('in'); BOOTSTRAP-SLIDER SOURCE CODE
//var left = Math.round(this.percent*this.width);
//this.tooltip.css('left', left - this.tooltip.outerWidth()/2); **************************************************/
this.over = true;
}, (function( $ ) {
hideTooltip: function(){ var ErrorMsgs = {
if (this.inDrag === false) { formatInvalidInputErrorMsg : function(input) {
this.tooltip.removeClass('in'); return "Invalid input value '" + input + "' passed in";
},
callingContextNotSliderInstance : "Calling context element does not have instance of Slider bound to it. Check your code to make sure the JQuery object returned from the call to the slider() initializer is calling the method"
};
/*************************************************
CONSTRUCTOR
**************************************************/
var Slider = function(element, options) {
createNewSlider.call(this, element, options);
return this;
};
function createNewSlider(element, options) {
/*************************************************
Create Markup
**************************************************/
if(typeof element === "string") {
this.element = document.querySelector(element);
} else if(element instanceof HTMLElement) {
this.element = element;
} }
this.over = false;
}, var origWidth = this.element.style.width;
var updateSlider = false;
layout: function(){ var parent = this.element.parentNode;
this.handle1Stype[this.stylePos] = this.percentage[0]+'%'; var sliderTrackSelection;
this.handle2Stype[this.stylePos] = this.percentage[1]+'%'; var sliderMinHandle;
if (this.orientation == 'vertical') { var sliderMaxHandle;
this.selectionElStyle.top = Math.min(this.percentage[0], this.percentage[1]) +'%';
this.selectionElStyle.height = Math.abs(this.percentage[0] - this.percentage[1]) +'%'; if (this.sliderElem) {
updateSlider = true;
} else { } else {
this.selectionElStyle.left = Math.min(this.percentage[0], this.percentage[1]) +'%'; /* Create elements needed for slider */
this.selectionElStyle.width = Math.abs(this.percentage[0] - this.percentage[1]) +'%'; this.sliderElem = document.createElement("div");
this.sliderElem.className = "slider";
/* Create slider track elements */
var sliderTrack = document.createElement("div");
sliderTrack.className = "slider-track";
sliderTrackSelection = document.createElement("div");
sliderTrackSelection.className = "slider-selection";
sliderMinHandle = document.createElement("div");
sliderMinHandle.className = "slider-handle min-slider-handle";
sliderMaxHandle = document.createElement("div");
sliderMaxHandle.className = "slider-handle max-slider-handle";
sliderTrack.appendChild(sliderTrackSelection);
sliderTrack.appendChild(sliderMinHandle);
sliderTrack.appendChild(sliderMaxHandle);
var createAndAppendTooltipSubElements = function(tooltipElem) {
var arrow = document.createElement("div");
arrow.className = "tooltip-arrow";
var inner = document.createElement("div");
inner.className = "tooltip-inner";
tooltipElem.appendChild(arrow);
tooltipElem.appendChild(inner);
};
/* Create tooltip elements */
var sliderTooltip = document.createElement("div");
sliderTooltip.className = "tooltip tooltip-main";
createAndAppendTooltipSubElements(sliderTooltip);
var sliderTooltipMin = document.createElement("div");
sliderTooltipMin.className = "tooltip tooltip-min";
createAndAppendTooltipSubElements(sliderTooltipMin);
var sliderTooltipMax = document.createElement("div");
sliderTooltipMax.className = "tooltip tooltip-max";
createAndAppendTooltipSubElements(sliderTooltipMax);
/* Append components to sliderElem */
this.sliderElem.appendChild(sliderTrack);
this.sliderElem.appendChild(sliderTooltip);
this.sliderElem.appendChild(sliderTooltipMin);
this.sliderElem.appendChild(sliderTooltipMax);
/* Append slider element to parent container, right before the original <input> element */
parent.insertBefore(this.sliderElem, this.element);
/* Hide original <input> element */
this.element.style.display = "none";
} }
if (this.range) { /* If JQuery exists, cache JQ references */
this.tooltipInner.text( if($) {
this.formater(this.value[0]) + this.$element = $(this.element);
' : ' + this.$sliderElem = $(this.sliderElem);
this.formater(this.value[1])
);
this.tooltip[0].style[this.stylePos] = this.size * (this.percentage[0] + (this.percentage[1] - this.percentage[0])/2)/100 - (this.orientation === 'vertical' ? this.tooltip.outerHeight()/2 : this.tooltip.outerWidth()/2) +'px';
} else {
this.tooltipInner.text(
this.formater(this.value[0])
);
this.tooltip[0].style[this.stylePos] = this.size * this.percentage[0]/100 - (this.orientation === 'vertical' ? this.tooltip.outerHeight()/2 : this.tooltip.outerWidth()/2) +'px';
} }
},
mousedown: function(ev) { /*************************************************
Process Options
**************************************************/
options = options ? options : {};
var optionTypes = Object.keys(this.defaultOptions);
for(var i = 0; i < optionTypes.length; i++) {
var optName = optionTypes[i];
// Touch: Get the original event: // First check if an option was passed in via the constructor
if (this.touchCapable && ev.type === 'touchstart') { var val = options[optName];
ev = ev.originalEvent; // If no data attrib, then check data atrributes
val = (typeof val !== 'undefined') ? val : getDataAttrib(this.element, optName);
// Finally, if nothing was specified, use the defaults
val = (val !== null) ? val : this.defaultOptions[optName];
// Set all options on the instance of the Slider
if(!this.options) {
this.options = {};
}
this.options[optName] = val;
} }
this.offset = this.picker.offset(); function getDataAttrib(element, optName) {
this.size = this.picker[0][this.sizePos]; var dataName = "data-slider-" + optName;
var dataValString = element.getAttribute(dataName);
try {
return JSON.parse(dataValString);
}
catch(err) {
return dataValString;
}
}
var percentage = this.getPercentage(ev); /*************************************************
Setup
if (this.range) { **************************************************/
var diff1 = Math.abs(this.percentage[0] - percentage); this.eventToCallbackMap = {};
var diff2 = Math.abs(this.percentage[1] - percentage); this.sliderElem.id = this.options.id;
this.dragged = (diff1 < diff2) ? 0 : 1;
} else { this.touchCapable = 'ontouchstart' in window || (window.DocumentTouch && document instanceof window.DocumentTouch);
this.dragged = 0;
this.tooltip = this.sliderElem.querySelector('.tooltip-main');
this.tooltipInner = this.tooltip.querySelector('.tooltip-inner');
this.tooltip_min = this.sliderElem.querySelector('.tooltip-min');
this.tooltipInner_min = this.tooltip_min.querySelector('.tooltip-inner');
this.tooltip_max = this.sliderElem.querySelector('.tooltip-max');
this.tooltipInner_max= this.tooltip_max.querySelector('.tooltip-inner');
if (updateSlider === true) {
// Reset classes
this._removeClass(this.sliderElem, 'slider-horizontal');
this._removeClass(this.sliderElem, 'slider-vertical');
this._removeClass(this.tooltip, 'hide');
this._removeClass(this.tooltip_min, 'hide');
this._removeClass(this.tooltip_max, 'hide');
// Undo existing inline styles for track
["left", "top", "width", "height"].forEach(function(prop) {
this._removeProperty(this.trackSelection, prop);
}, this);
// Undo inline styles on handles
[this.handle1, this.handle2].forEach(function(handle) {
this._removeProperty(handle, 'left');
this._removeProperty(handle, 'top');
}, this);
// Undo inline styles and classes on tooltips
[this.tooltip, this.tooltip_min, this.tooltip_max].forEach(function(tooltip) {
this._removeProperty(tooltip, 'left');
this._removeProperty(tooltip, 'top');
this._removeProperty(tooltip, 'margin-left');
this._removeProperty(tooltip, 'margin-top');
this._removeClass(tooltip, 'right');
this._removeClass(tooltip, 'top');
}, this);
} }
this.percentage[this.dragged] = percentage; if(this.options.orientation === 'vertical') {
this.layout(); this._addClass(this.sliderElem,'slider-vertical');
this.stylePos = 'top';
this.mousePos = 'pageY';
this.sizePos = 'offsetHeight';
this._addClass(this.tooltip, 'right');
this.tooltip.style.left = '100%';
this._addClass(this.tooltip_min, 'right');
this.tooltip_min.style.left = '100%';
if (this.touchCapable) { this._addClass(this.tooltip_max, 'right');
// Touch: Bind touch events: this.tooltip_max.style.left = '100%';
$(document).on({
touchmove: $.proxy(this.mousemove, this),
touchend: $.proxy(this.mouseup, this)
});
} else { } else {
$(document).on({ this._addClass(this.sliderElem, 'slider-horizontal');
mousemove: $.proxy(this.mousemove, this), this.sliderElem.style.width = origWidth;
mouseup: $.proxy(this.mouseup, this)
}); this.options.orientation = 'horizontal';
this.stylePos = 'left';
this.mousePos = 'pageX';
this.sizePos = 'offsetWidth';
this._addClass(this.tooltip, 'top');
this.tooltip.style.top = -this.tooltip.outerHeight - 14 + 'px';
this._addClass(this.tooltip_min, 'top');
this.tooltip_min.style.top = -this.tooltip_min.outerHeight - 14 + 'px';
this._addClass(this.tooltip_max, 'top');
this.tooltip_max.style.top = -this.tooltip_max.outerHeight - 14 + 'px';
} }
this.inDrag = true; if (this.options.value instanceof Array) {
var val = this.calculateValue(); this.options.range = true;
this.element.trigger({ } else if (this.options.range) {
type: 'slideStart', // User wants a range, but value is not an array
value: val this.options.value = [this.options.value, this.options.max];
}).trigger({ }
type: 'slide',
value: val
});
return false;
},
mousemove: function(ev) { this.trackSelection = sliderTrackSelection || this.trackSelection;
if (this.options.selection === 'none') {
// Touch: Get the original event: this._addClass(this.trackSelection, 'hide');
if (this.touchCapable && ev.type === 'touchmove') {
ev = ev.originalEvent;
} }
var percentage = this.getPercentage(ev); this.handle1 = sliderMinHandle || this.handle1;
if (this.range) { this.handle2 = sliderMaxHandle || this.handle2;
if (this.dragged === 0 && this.percentage[1] < percentage) {
this.percentage[0] = this.percentage[1]; if (updateSlider === true) {
this.dragged = 1; // Reset classes
} else if (this.dragged === 1 && this.percentage[0] > percentage) { this._removeClass(this.handle1, 'round triangle');
this.percentage[1] = this.percentage[0]; this._removeClass(this.handle2, 'round triangle hide');
this.dragged = 0;
}
} }
this.percentage[this.dragged] = percentage;
this.layout();
var val = this.calculateValue();
this.element
.trigger({
type: 'slide',
value: val
})
.data('value', val)
.prop('value', val);
return false;
},
mouseup: function(ev) { var availableHandleModifiers = ['round', 'triangle', 'custom'];
var isValidHandleType = availableHandleModifiers.indexOf(this.options.handle) !== -1;
if (isValidHandleType) {
this._addClass(this.handle1, this.options.handle);
this._addClass(this.handle2, this.options.handle);
}
this.offset = this._offset(this.sliderElem);
this.size = this.sliderElem[this.sizePos];
this.setValue(this.options.value);
/******************************************
Bind Event Listeners
******************************************/
// Bind keyboard handlers
this.handle1Keydown = this._keydown.bind(this, 0);
this.handle1.addEventListener("keydown", this.handle1Keydown, false);
this.handle2Keydown = this._keydown.bind(this, 0);
this.handle2.addEventListener("keydown", this.handle2Keydown, false);
if (this.touchCapable) { if (this.touchCapable) {
// Touch: Bind touch events: // Bind touch handlers
$(document).off({ this.mousedown = this._mousedown.bind(this);
touchmove: this.mousemove, this.sliderElem.addEventListener("touchstart", this.mousedown, false);
touchend: this.mouseup
});
} else { } else {
$(document).off({ // Bind mouse handlers
mousemove: this.mousemove, this.mousedown = this._mousedown.bind(this);
mouseup: this.mouseup this.sliderElem.addEventListener("mousedown", this.mousedown, false);
});
} }
this.inDrag = false; // Bind tooltip-related handlers
if (this.over == false) { if(this.options.tooltip === 'hide') {
this.hideTooltip(); this._addClass(this.tooltip, 'hide');
} this._addClass(this.tooltip_min, 'hide');
this.element; this._addClass(this.tooltip_max, 'hide');
var val = this.calculateValue(); } else if(this.options.tooltip === 'always') {
this.element this._showTooltip();
.trigger({ this._alwaysShowTooltip = true;
type: 'slideStop',
value: val
})
.data('value', val)
.prop('value', val);
return false;
},
calculateValue: function() {
var val;
if (this.range) {
val = [
(this.min + Math.round((this.diff * this.percentage[0]/100)/this.step)*this.step),
(this.min + Math.round((this.diff * this.percentage[1]/100)/this.step)*this.step)
];
this.value = val;
} else { } else {
val = (this.min + Math.round((this.diff * this.percentage[0]/100)/this.step)*this.step); this.showTooltip = this._showTooltip.bind(this);
this.value = [val, this.value[1]]; this.hideTooltip = this._hideTooltip.bind(this);
}
return val;
},
getPercentage: function(ev) { this.sliderElem.addEventListener("mouseenter", this.showTooltip, false);
if (this.touchCapable) { this.sliderElem.addEventListener("mouseleave", this.hideTooltip, false);
ev = ev.touches[0];
this.handle1.addEventListener("focus", this.showTooltip, false);
this.handle1.addEventListener("blur", this.hideTooltip, false);
this.handle2.addEventListener("focus", this.showTooltip, false);
this.handle2.addEventListener("blur", this.hideTooltip, false);
} }
var percentage = (ev[this.mousePos] - this.offset[this.stylePos])*100/this.size;
percentage = Math.round(percentage/this.percentage[2])*this.percentage[2]; if(this.options.enabled) {
return Math.max(0, Math.min(100, percentage)); this.enable();
}, } else {
this.disable();
getValue: function() {
if (this.range) {
return this.value;
} }
return this.value[0]; }
},
setValue: function(val) { /*************************************************
this.value = val;
INSTANCE PROPERTIES/METHODS
if (this.range) { - Any methods bound to the prototype are considered
this.value[0] = Math.max(this.min, Math.min(this.max, this.value[0])); part of the plugin's `public` interface
this.value[1] = Math.max(this.min, Math.min(this.max, this.value[1]));
} else { **************************************************/
this.value = [ Math.max(this.min, Math.min(this.max, this.value))]; Slider.prototype = {
this.handle2.addClass('hide'); _init: function() {}, // NOTE: Must exist to support bridget
if (this.selection == 'after') {
this.value[1] = this.max; constructor: Slider,
defaultOptions: {
id: "",
min: 0,
max: 10,
step: 1,
precision: 0,
orientation: 'horizontal',
value: 5,
range: false,
selection: 'before',
tooltip: 'show',
tooltip_split: false,
handle: 'round',
reversed: false,
enabled: true,
formatter: function(val) {
if(val instanceof Array) {
return val[0] + " : " + val[1];
} else {
return val;
}
},
natural_arrow_keys: false
},
over: false,
inDrag: false,
getValue: function() {
if (this.options.range) {
return this.options.value;
}
return this.options.value[0];
},
setValue: function(val, triggerSlideEvent) {
if (!val) {
val = 0;
}
this.options.value = this._validateInputValue(val);
var applyPrecision = this._applyPrecision.bind(this);
if (this.options.range) {
this.options.value[0] = applyPrecision(this.options.value[0]);
this.options.value[1] = applyPrecision(this.options.value[1]);
this.options.value[0] = Math.max(this.options.min, Math.min(this.options.max, this.options.value[0]));
this.options.value[1] = Math.max(this.options.min, Math.min(this.options.max, this.options.value[1]));
} else { } else {
this.value[1] = this.min; this.options.value = applyPrecision(this.options.value);
this.options.value = [ Math.max(this.options.min, Math.min(this.options.max, this.options.value))];
this._addClass(this.handle2, 'hide');
if (this.options.selection === 'after') {
this.options.value[1] = this.options.max;
} else {
this.options.value[1] = this.options.min;
}
} }
this.diff = this.options.max - this.options.min;
if (this.diff > 0) {
this.percentage = [
(this.options.value[0] - this.options.min) * 100 / this.diff,
(this.options.value[1] - this.options.min) * 100 / this.diff,
this.options.step * 100 / this.diff
];
} else {
this.percentage = [0, 0, 100];
}
this._layout();
var sliderValue = this.options.range ? this.options.value : this.options.value[0];
this._setDataVal(sliderValue);
if(triggerSlideEvent === true) {
this._trigger('slide', sliderValue);
}
return this;
},
destroy: function(){
// Remove event handlers on slider elements
this._removeSliderEventHandlers();
// Remove the slider from the DOM
this.sliderElem.parentNode.removeChild(this.sliderElem);
/* Show original <input> element */
this.element.style.display = "";
// Clear out custom event bindings
this._cleanUpEventCallbacksMap();
// Remove data values
this.element.removeAttribute("data");
// Remove JQuery handlers/data
if($) {
this._unbindJQueryEventHandlers();
this.$element.removeData('slider');
}
},
disable: function() {
this.options.enabled = false;
this.handle1.removeAttribute("tabindex");
this.handle2.removeAttribute("tabindex");
this._addClass(this.sliderElem, 'slider-disabled');
this._trigger('slideDisabled');
return this;
},
enable: function() {
this.options.enabled = true;
this.handle1.setAttribute("tabindex", 0);
this.handle2.setAttribute("tabindex", 0);
this._removeClass(this.sliderElem, 'slider-disabled');
this._trigger('slideEnabled');
return this;
},
toggle: function() {
if(this.options.enabled) {
this.disable();
} else {
this.enable();
}
return this;
},
isEnabled: function() {
return this.options.enabled;
},
on: function(evt, callback) {
if($) {
this.$element.on(evt, callback);
this.$sliderElem.on(evt, callback);
} else {
this._bindNonQueryEventHandler(evt, callback);
}
return this;
},
getAttribute: function(attribute) {
if(attribute) {
return this.options[attribute];
} else {
return this.options;
}
},
setAttribute: function(attribute, value) {
this.options[attribute] = value;
return this;
},
refresh: function() {
this._removeSliderEventHandlers();
createNewSlider.call(this, this.element, this.options);
if($) {
// Bind new instance of slider to the element
$.data(this.element, 'slider', this);
}
return this;
},
/******************************+
HELPERS
- Any method that is not part of the public interface.
- Place it underneath this comment block and write its signature like so:
_fnName : function() {...}
********************************/
_removeSliderEventHandlers: function() {
// Remove event listeners from handle1
this.handle1.removeEventListener("keydown", this.handle1Keydown, false);
this.handle1.removeEventListener("focus", this.showTooltip, false);
this.handle1.removeEventListener("blur", this.hideTooltip, false);
// Remove event listeners from handle2
this.handle2.removeEventListener("keydown", this.handle2Keydown, false);
this.handle2.removeEventListener("focus", this.handle2Keydown, false);
this.handle2.removeEventListener("blur", this.handle2Keydown, false);
// Remove event listeners from sliderElem
this.sliderElem.removeEventListener("mouseenter", this.showTooltip, false);
this.sliderElem.removeEventListener("mouseleave", this.hideTooltip, false);
this.sliderElem.removeEventListener("touchstart", this.mousedown, false);
this.sliderElem.removeEventListener("mousedown", this.mousedown, false);
},
_bindNonQueryEventHandler: function(evt, callback) {
if(this.eventToCallbackMap[evt]===undefined) {
this.eventToCallbackMap[evt] = [];
}
this.eventToCallbackMap[evt].push(callback);
},
_cleanUpEventCallbacksMap: function() {
var eventNames = Object.keys(this.eventToCallbackMap);
for(var i = 0; i < eventNames.length; i++) {
var eventName = eventNames[i];
this.eventToCallbackMap[eventName] = null;
}
},
_showTooltip: function() {
if (this.options.tooltip_split === false ){
this._addClass(this.tooltip, 'in');
} else {
this._addClass(this.tooltip_min, 'in');
this._addClass(this.tooltip_max, 'in');
}
this.over = true;
},
_hideTooltip: function() {
if (this.inDrag === false && this.alwaysShowTooltip !== true) {
this._removeClass(this.tooltip, 'in');
this._removeClass(this.tooltip_min, 'in');
this._removeClass(this.tooltip_max, 'in');
}
this.over = false;
},
_layout: function() {
var positionPercentages;
if(this.options.reversed) {
positionPercentages = [ 100 - this.percentage[0], this.percentage[1] ];
} else {
positionPercentages = [ this.percentage[0], this.percentage[1] ];
}
this.handle1.style[this.stylePos] = positionPercentages[0]+'%';
this.handle2.style[this.stylePos] = positionPercentages[1]+'%';
if (this.options.orientation === 'vertical') {
this.trackSelection.style.top = Math.min(positionPercentages[0], positionPercentages[1]) +'%';
this.trackSelection.style.height = Math.abs(positionPercentages[0] - positionPercentages[1]) +'%';
} else {
this.trackSelection.style.left = Math.min(positionPercentages[0], positionPercentages[1]) +'%';
this.trackSelection.style.width = Math.abs(positionPercentages[0] - positionPercentages[1]) +'%';
var offset_min = this.tooltip_min.getBoundingClientRect();
var offset_max = this.tooltip_max.getBoundingClientRect();
if (offset_min.right > offset_max.left) {
this._removeClass(this.tooltip_max, 'top');
this._addClass(this.tooltip_max, 'bottom');
this.tooltip_max.style.top = 18 + 'px';
} else {
this._removeClass(this.tooltip_max, 'bottom');
this._addClass(this.tooltip_max, 'top');
this.tooltip_max.style.top = -30 + 'px';
}
}
var formattedTooltipVal;
if (this.options.range) {
formattedTooltipVal = this.options.formatter(this.options.value);
this._setText(this.tooltipInner, formattedTooltipVal);
this.tooltip.style[this.stylePos] = (positionPercentages[1] + positionPercentages[0])/2 + '%';
if (this.options.orientation === 'vertical') {
this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px');
}
if (this.options.orientation === 'vertical') {
this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px');
}
var innerTooltipMinText = this.options.formatter(this.options.value[0]);
this._setText(this.tooltipInner_min, innerTooltipMinText);
var innerTooltipMaxText = this.options.formatter(this.options.value[1]);
this._setText(this.tooltipInner_max, innerTooltipMaxText);
this.tooltip_min.style[this.stylePos] = positionPercentages[0] + '%';
if (this.options.orientation === 'vertical') {
this._css(this.tooltip_min, 'margin-top', -this.tooltip_min.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip_min, 'margin-left', -this.tooltip_min.offsetWidth / 2 + 'px');
}
this.tooltip_max.style[this.stylePos] = positionPercentages[1] + '%';
if (this.options.orientation === 'vertical') {
this._css(this.tooltip_max, 'margin-top', -this.tooltip_max.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip_max, 'margin-left', -this.tooltip_max.offsetWidth / 2 + 'px');
}
} else {
formattedTooltipVal = this.options.formatter(this.options.value[0]);
this._setText(this.tooltipInner, formattedTooltipVal);
this.tooltip.style[this.stylePos] = positionPercentages[0] + '%';
if (this.options.orientation === 'vertical') {
this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px');
}
}
},
_removeProperty: function(element, prop) {
if (element.style.removeProperty) {
element.style.removeProperty(prop);
} else {
element.style.removeAttribute(prop);
}
},
_mousedown: function(ev) {
if(!this.options.enabled) {
return false;
}
this._triggerFocusOnHandle();
this.offset = this._offset(this.sliderElem);
this.size = this.sliderElem[this.sizePos];
var percentage = this._getPercentage(ev);
if (this.options.range) {
var diff1 = Math.abs(this.percentage[0] - percentage);
var diff2 = Math.abs(this.percentage[1] - percentage);
this.dragged = (diff1 < diff2) ? 0 : 1;
} else {
this.dragged = 0;
}
this.percentage[this.dragged] = this.options.reversed ? 100 - percentage : percentage;
this._layout();
this.mousemove = this._mousemove.bind(this);
this.mouseup = this._mouseup.bind(this);
if (this.touchCapable) {
// Touch: Bind touch events:
document.addEventListener("touchmove", this.mousemove, false);
document.addEventListener("touchend", this.mouseup, false);
} else {
// Bind mouse events:
document.addEventListener("mousemove", this.mousemove, false);
document.addEventListener("mouseup", this.mouseup, false);
}
this.inDrag = true;
var val = this._calculateValue();
this._trigger('slideStart', val);
this._setDataVal(val);
this.setValue(val);
this._pauseEvent(ev);
return true;
},
_triggerFocusOnHandle: function(handleIdx) {
if(handleIdx === 0) {
this.handle1.focus();
}
if(handleIdx === 1) {
this.handle2.focus();
}
},
_keydown: function(handleIdx, ev) {
if(!this.options.enabled) {
return false;
}
var dir;
switch (ev.keyCode) {
case 37: // left
case 40: // down
dir = -1;
break;
case 39: // right
case 38: // up
dir = 1;
break;
}
if (!dir) {
return;
}
// use natural arrow keys instead of from min to max
if (this.options.natural_arrow_keys) {
var ifVerticalAndNotReversed = (this.options.orientation === 'vertical' && !this.options.reversed);
var ifHorizontalAndReversed = (this.options.orientation === 'horizontal' && this.options.reversed);
if (ifVerticalAndNotReversed || ifHorizontalAndReversed) {
dir = dir * -1;
}
}
var oneStepValuePercentageChange = dir * this.percentage[2];
var percentage = this.percentage[handleIdx] + oneStepValuePercentageChange;
if (percentage > 100) {
percentage = 100;
} else if (percentage < 0) {
percentage = 0;
}
this.dragged = handleIdx;
this._adjustPercentageForRangeSliders(percentage);
this.percentage[this.dragged] = percentage;
this._layout();
var val = this._calculateValue();
this._trigger('slideStart', val);
this._setDataVal(val);
this.setValue(val, true);
this._trigger('slideStop', val);
this._setDataVal(val);
this._pauseEvent(ev);
return false;
},
_pauseEvent: function(ev) {
if(ev.stopPropagation) {
ev.stopPropagation();
}
if(ev.preventDefault) {
ev.preventDefault();
}
ev.cancelBubble=true;
ev.returnValue=false;
},
_mousemove: function(ev) {
if(!this.options.enabled) {
return false;
}
var percentage = this._getPercentage(ev);
this._adjustPercentageForRangeSliders(percentage);
this.percentage[this.dragged] = this.options.reversed ? 100 - percentage : percentage;
this._layout();
var val = this._calculateValue();
this.setValue(val, true);
return false;
},
_adjustPercentageForRangeSliders: function(percentage) {
if (this.options.range) {
if (this.dragged === 0 && this.percentage[1] < percentage) {
this.percentage[0] = this.percentage[1];
this.dragged = 1;
} else if (this.dragged === 1 && this.percentage[0] > percentage) {
this.percentage[1] = this.percentage[0];
this.dragged = 0;
}
}
},
_mouseup: function() {
if(!this.options.enabled) {
return false;
}
if (this.touchCapable) {
// Touch: Unbind touch event handlers:
document.removeEventListener("touchmove", this.mousemove, false);
document.removeEventListener("touchend", this.mouseup, false);
} else {
// Unbind mouse event handlers:
document.removeEventListener("mousemove", this.mousemove, false);
document.removeEventListener("mouseup", this.mouseup, false);
}
this.inDrag = false;
if (this.over === false) {
this._hideTooltip();
}
var val = this._calculateValue();
this._layout();
this._setDataVal(val);
this._trigger('slideStop', val);
return false;
},
_calculateValue: function() {
var val;
if (this.options.range) {
val = [this.options.min,this.options.max];
if (this.percentage[0] !== 0){
val[0] = (Math.max(this.options.min, this.options.min + Math.round((this.diff * this.percentage[0]/100)/this.options.step)*this.options.step));
val[0] = this._applyPrecision(val[0]);
}
if (this.percentage[1] !== 100){
val[1] = (Math.min(this.options.max, this.options.min + Math.round((this.diff * this.percentage[1]/100)/this.options.step)*this.options.step));
val[1] = this._applyPrecision(val[1]);
}
this.options.value = val;
} else {
val = (this.options.min + Math.round((this.diff * this.percentage[0]/100)/this.options.step)*this.options.step);
if (val < this.options.min) {
val = this.options.min;
}
else if (val > this.options.max) {
val = this.options.max;
}
val = parseFloat(val);
val = this._applyPrecision(val);
this.options.value = [val, this.options.value[1]];
}
return val;
},
_applyPrecision: function(val) {
var precision = this.options.precision || this._getNumDigitsAfterDecimalPlace(this.step);
return this._applyToFixedAndParseFloat(val, precision);
},
_getNumDigitsAfterDecimalPlace: function(num) {
var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) { return 0; }
return Math.max(0, (match[1] ? match[1].length : 0) - (match[2] ? +match[2] : 0));
},
_applyToFixedAndParseFloat: function(num, toFixedInput) {
var truncatedNum = num.toFixed(toFixedInput);
return parseFloat(truncatedNum);
},
/*
Credits to Mike Samuel for the following method!
Source: http://stackoverflow.com/questions/10454518/javascript-how-to-retrieve-the-number-of-decimals-of-a-string-number
*/
_getPercentage: function(ev) {
if (this.touchCapable && (ev.type === 'touchstart' || ev.type === 'touchmove')) {
ev = ev.touches[0];
}
var percentage = (ev[this.mousePos] - this.offset[this.stylePos])*100/this.size;
percentage = Math.round(percentage/this.percentage[2])*this.percentage[2];
return Math.max(0, Math.min(100, percentage));
},
_validateInputValue: function(val) {
if(typeof val === 'number') {
return val;
} else if(val instanceof Array) {
this._validateArray(val);
return val;
} else {
throw new Error( ErrorMsgs.formatInvalidInputErrorMsg(val) );
}
},
_validateArray: function(val) {
for(var i = 0; i < val.length; i++) {
var input = val[i];
if (typeof input !== 'number') { throw new Error( ErrorMsgs.formatInvalidInputErrorMsg(input) ); }
}
},
_setDataVal: function(val) {
var value = "value: '" + val + "'";
this.element.setAttribute('data', value);
this.element.setAttribute('value', val);
},
_trigger: function(evt, val) {
val = val || undefined;
var callbackFnArray = this.eventToCallbackMap[evt];
if(callbackFnArray && callbackFnArray.length) {
for(var i = 0; i < callbackFnArray.length; i++) {
var callbackFn = callbackFnArray[i];
callbackFn(val);
}
}
/* If JQuery exists, trigger JQuery events */
if($) {
this._triggerJQueryEvent(evt, val);
}
},
_triggerJQueryEvent: function(evt, val) {
var eventData = {
type: evt,
value: val
};
this.$element.trigger(eventData);
this.$sliderElem.trigger(eventData);
},
_unbindJQueryEventHandlers: function() {
this.$element.off();
this.$sliderElem.off();
},
_setText: function(element, text) {
if(typeof element.innerText !== "undefined") {
element.innerText = text;
} else if(typeof element.textContent !== "undefined") {
element.textContent = text;
}
},
_removeClass: function(element, classString) {
var classes = classString.split(" ");
var newClasses = element.className;
for(var i = 0; i < classes.length; i++) {
var classTag = classes[i];
var regex = new RegExp("(?:\\s|^)" + classTag + "(?:\\s|$)");
newClasses = newClasses.replace(regex, " ");
}
element.className = newClasses.trim();
},
_addClass: function(element, classString) {
var classes = classString.split(" ");
var newClasses = element.className;
for(var i = 0; i < classes.length; i++) {
var classTag = classes[i];
var regex = new RegExp("(?:\\s|^)" + classTag + "(?:\\s|$)");
var ifClassExists = regex.test(newClasses);
if(!ifClassExists) {
newClasses += " " + classTag;
}
}
element.className = newClasses.trim();
},
_offset: function (obj) {
var ol = 0;
var ot = 0;
if (obj.offsetParent) {
do {
ol += obj.offsetLeft;
ot += obj.offsetTop;
} while (obj = obj.offsetParent);
}
return {
left: ol,
top: ot
};
},
_css: function(elementRef, styleName, value) {
elementRef.style[styleName] = value;
} }
this.diff = this.max - this.min; };
this.percentage = [
(this.value[0]-this.min)*100/this.diff, /*********************************
(this.value[1]-this.min)*100/this.diff,
this.step*100/this.diff Attach to global namespace
];
this.layout(); *********************************/
} if($) {
}; var namespace = $.fn.slider ? 'bootstrapSlider' : 'slider';
$.bridget(namespace, Slider);
$.fn.slider = function ( option, val ) { } else {
return this.each(function () { window.Slider = Slider;
var $this = $(this),
data = $this.data('slider'),
options = typeof option === 'object' && option;
if (!data) {
$this.data('slider', (data = new Slider(this, $.extend({}, $.fn.slider.defaults,options))));
}
if (typeof option == 'string') {
data[option](val);
}
})
};
$.fn.slider.defaults = {
min: 0,
max: 10,
step: 1,
orientation: 'horizontal',
value: 5,
selection: 'before',
tooltip: 'show',
handle: 'round',
formater: function(value) {
return value;
} }
};
$.fn.slider.Constructor = Slider;
}( window.jQuery ); })( $ );
\ No newline at end of file
})( window.jQuery );
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册