我不确定这是否是最好的方法,但这个解决方案最终对我有用。我在这里回答,以防其他人遇到同样的问题。
查看 jQuery API,看起来活动句柄是根据某种距离计算的,而我想要的只是被点击的句柄。
我覆盖了 jQuery UI _mouseCapture 事件并将其自定义为对点击敏感。它还需要一些硬设置的 CSS 类检测来确定哪个句柄是活动句柄。
通过这样做,我能够避免修改任何库文件,并且只更改了少量原始函数。
// Create the slider.
var slider = $('.slider').slider({//OPTIONS HERE});
// Get the slider and replace the _mouseCapture function with a custom one.
slider.data('ui-slider')._mouseCapture = function(event) {
var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle,
that = this,
o = this.options;
if ( o.disabled ) {
return false;
}
this.elementSize = {
width: this.element.outerWidth(),
height: this.element.outerHeight()
};
this.elementOffset = this.element.offset();
// Get the element that the click was triggered on and set that to closestHandle. There was a bunch of distance calculation here previously - that has been removed.
currentHandle = $(event.toElement);
closestHandle = currentHandle;
// 'custom-handle-1' is a custom class I give to the left slider handle
// I know that my sliders will only have 2 values (so index will either be 0 or 1 always).
if (closestHandle.hasClass('custom-handle-1')) {
index = 0;
}
else {
index = 1;
}
allowed = this._start( event, index );
if ( allowed === false ) {
return false;
}
this._mouseSliding = true;
this._handleIndex = index;
this._addClass( closestHandle, null, "ui-state-active" );
closestHandle.trigger( "focus" );
offset = closestHandle.offset();
mouseOverHandle = !$( event.target ).parents().addBack().is( ".ui-slider-handle" );
this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
left: event.pageX - offset.left - ( closestHandle.width() / 2 ),
top: event.pageY - offset.top -
( closestHandle.height() / 2 ) -
( parseInt( closestHandle.css( "borderTopWidth" ), 10 ) || 0 ) -
( parseInt( closestHandle.css( "borderBottomWidth" ), 10 ) || 0 ) +
( parseInt( closestHandle.css( "marginTop" ), 10 ) || 0 )
};
if ( !this.handles.hasClass( "ui-state-hover" ) ) {
this._slide( event, index, normValue );
}
this._animateOff = true;
return true;
};
缺点是这可能与 jQuery UI 的未来版本不兼容,但这是未来的问题(目前是 1.12.1)。