这是一个主要从头开始编写的滑块。也就是说,不使用任何 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);
}();
}