伪造带有输入范围的拨动开关,处理自定义范围

Faking a toggle switch with an Input Range, dealing with custom range

我需要伪造一个带有输入范围的拨动开关。 这个想法是创建一个短范围,只有 2 个值,最小值和最大值。 css 按钮将匹配范围的一端。到目前为止,您单击它,包含范围的 div 会移动一点,将游侠的另一端带到您的鼠标下方。

我有这个功能,适用于页面上的所有输入范围。但我只需要将它应用于某些 类,而不是全部。但是我找不到正确的语法并且它不起作用。

Javascript:

$('input[type="range"]').on('change', function() {
$('div#launcher01').css('margin-top', parseInt($(this).val()  ) > 0 ? parseInt($(this).val()  ) + 'px' : '0px');
    });

CSS:

.fakbl input {
height: 50px;
width: 50px;

HTML:

<div id="launcher01">
<div class="fakbl">
<input type="range" id="launch01" name="launch01" min="0" max="50" step="50"" />
</div>
</div> 

Fiddle

由于您已经在使用 jQuery,您可以将 widget-maker 表述为 jQuery 插件,如下所示:

$.fn.rangeButton = function(containerSelector) {
    return this.each(function() {
        var $self = $(this);
        $self.on('change', function() {
            $self.closest(containerSelector).css('margin-left', ($self.val()/3) > 0 ? ($self.val()/3) + 'px' : '0px');
        }).trigger('change'); // trigger 'change' immediately to initialize everything.
    });
};

现在,在您的每个范围上调用小部件,并为适当的容器传递一个选择器:

$('#launcher01 input[type="range"]').rangeButton('#launcher01');
$('#launcher02 input[type="range"]').rangeButton('#launcher02');

Demo

或者,通过为所有容器提供相同的 class,您可以使用单个命令调用所有小部件:

$('.myClass input[type="range"]').rangeButton('.myClass');

Demo

请问可以求精吗?

我完成了假按钮。正如您在 FIDDLE

中看到的

(白框会消失,我给它添加了一些不透明度只是为了表明按钮正在工作) 红色框(由于我的错误代码部分现在是绿色)在背景中,我需要它根据状态改变颜色。我试过了,但没用。 这里的代码:

 $.fn.rangeButton = function(containerSelector) {
        return this.each(function() {
            var $self = $(this);
            $self.on('change', function() {  
                $self.closest(containerSelector).css('margin-left',     ($self.val()/3) > 0 ? ($self.val()/3) + 'px' : '0px');


   //   this part is not working, if you remove this part, the button works flawlessy
          if ($self = 100) {
              document.getElementById("fakbuttonsfondo01").style.backgroundColor="rgb(0, 191, 1)"; 
          } else {
              document.getElementById("fakbuttonsfondo01").style.backgroundColor="rgb(0, 0, 255)"; 
          }  
    //   end of buggy code



            }).trigger('change'); // trigger 'change' immediately to initialize everything.
        });
    };

    $('#launcher01 input[type="range"]').rangeButton('#launcher01');
    $('#launcher02 input[type="range"]').rangeButton('#launcher02');

谢谢:)