これはほとんどゼロから書かれたスライダーです。つまり、UI ライブラリを使用しません。私は jQuery、_、およびバックボーンを使用しますが、それらを気にしない場合は、同じことを行うブラウザー API のより原始的なバージョンに置き換えることができます。http://jsfiddle.net/shyamh/gBNAg/の完全なサンプルタッチ イベントのサポートは追加されていませんが、接続するのは難しくありません。
function slider(id, width) {
var _i = this,
// todo - can we refactor to get _thumbWidth from element styles?
_thumbWidth = 24,
_slideRange = width,
// View template for control. Typically this would be outside the class,
// so it's reused between multiple instance of this control.
// The id is bound as a paremeter in the template. There may be other parameters.
//
_t = '<div id="<%=id%>" class="slider" style="width:<%=width%>px;">' +
' <div id="<%=id%>_track" class="sliderTrack"></div>' +
' <div id="<%=id%>_thumbcontainer" class="sliderThumbContainer" style="width:' + _thumbWidth + 'px">' +
' <div id="<%=id%>_thumb" class="sliderThumb"></div>' +
' </div>' +
'</div>',
_currentValue = 0,
_$el = $(_.template(_t, { id: id, width: (width || 100) })),
_el = _$el[0],
_elTrack = $('#' + id + '_track:first', _el)[0],
_elThumbContainer = $('#' + id + '_thumbcontainer:first', _el)[0];
_.extend(_i, Backbone.Events);
function x2Percent(x) {
if (x < 0) {
return 0;
} else {
var p = x / _slideRange * 100;
if (p > 100) { p = 100; }
return p;
}
}
function moveThumbToX(x) {
var offsetLeft = _$el.offset().left,
p = x2Percent(x - offsetLeft),
newX = (Math.round(p / 100 * _slideRange) - _thumbWidth / 2);
newX = (newX < 0) ? 0 : ((newX > (width - _thumbWidth)) ? (width - _thumbWidth) : newX) ;
_elThumbContainer.style.left = newX + "px";
_currentValue = p;
}
function _elClick(e) {
moveThumbToX(e.x);
// todo - fire backbone event for slider changed event
}
function _elThumbContainerMouseDown(e) {
document.addEventListener("mousemove", _mouseMove);
document.addEventListener("mouseup", _mouseUp);
e.preventDefault();
e.stopPropagation();
// todo - fire backbone event for slider drag-started event
}
function _mouseMove(e) {
var x = e.x;
e.preventDefault();
requestAnimationFrame(function() {
moveThumbToX(e.x);
// todo - fire backbone event for slider dragging event
});
}
function _mouseUp(e) {
e.preventDefault();
document.removeEventListener("mousemove", _mouseMove);
document.removeEventListener("mouseup", _mouseUp);
// todo - fire backbone event for slider drag-ended event
}
// set the value to p, where p is between 0..100
_i.setValue = function(p) {
moveThumbToX(Math.round(p / 100 * _slideRange));
}
_i.getElement = function () {
return _el;
}
var _ctor = function () {
_el.addEventListener("click", _elClick);
_elThumbContainer.addEventListener("mousedown", _elThumbContainerMouseDown);
}();
}