JQuery UI Slider with Multiple handles: How to stop the handles from crossing?

一曲冷凌霜 提交于 2019-12-04 17:49:58

In the slide event you can constrain the handle movement by checking the slider values and returning true to allow the slide or false to prevent it (see the jQuery UI docs for more information)

What code are you using for the Jquery slider? Looking at the range slider demo, it has two handles and its not possible to cross them.

As @madcapnmckay pointed out, if you have a slider with two handles and the range: true in the options the handles cannot be dragged past each other.

I was having a problem where it wasn't constraining properly but it turned out I had a string 'true' instead of a boolean true

Check this solution:

slide : function( event, ui ) {
        //Actual Handle Selected
        var handleIndex = $(ui.handle).index()-1;

        var diffA, diffB;

        //Check with right handles
        if(handleIndex > 0)
            diffA = ui.values[handleIndex] - ui.values[handleIndex-1];

        //Check with left handles
        if(handleIndex < ui.values.length-1)
            diffB = ui.values[handleIndex+1] - ui.values[handleIndex];

        if (diffA <= 0 || diffB <= 0) { /*checks for the values and compares*/
            return false;
        }
   }

I'm a bit late to the party here, but I wanted to share my most compact-yet-readable way to do this. Technically it's pretty similar to @tototresde's answer.

slide: function (e, ui) {
  // Prevent crossing and overlapping of slider handles.
  if (ui.values[(ui.handleIndex - 1)] >= ui.value ||
      ui.values[(ui.handleIndex + 1)] <= ui.value) {
    return false;
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!