2017-05-17 37 views
0

我需要假设一个具有输入范围的切换开关。 这个想法是创建一个短距离,只有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

回答

0

既然你已经使用jQuery,您可以PHR ASE你的部件制造商作为一个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

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

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

Demo

+0

哇,这是惊人的流浪汉!非常感谢你,我真的很感激,我花了很多时间尝试,而你做得很直。 –

+0

不用担心。练习(和年龄大)会变得更容易。 –

+0

:)太棒了,我是一个初学者,我希望我的代码能够这么好。 –

0

请问细化吗?

我完成了假按钮。正如你在这个FIDDLE

(白框就会消失,我添加了一些不透明度为它只是表明该按钮工作) 红色框见(现为绿色,由于我的bug的代码部分)是在背景和我需要它来改变颜色取决于状态。我试过这个,但它不起作用。 下面的代码:

$.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'); 

谢谢:)