通过JavaScript拖动平滑滑块

时间:2015-09-15 11:28:39

标签: javascript jquery html json

我有以下代码。它只是循环遍历和Object并在HTML中显示对象键作为滑动条。

jQuery(function($) {
   $('#threshold').change(updateThreshold);
   function updateThreshold () {
       var thresholdIndex = parseInt($('#threshold').val(), 10);
       $("#foldchange_threshold").html(foldchange_thresholds[thresholdIndex]);
   };

   var foldchange_thresholds = [];
    var mydata = {"3":["c","d"], 
                  "3.5":["j","k"], 
                  "1.5":["a","b"], 
                  "0.5":["c","d"], 
                  "2.0":["e","f"], 
                  "2.5":["x","y"] };
    
    Object.keys(mydata).sort().forEach(function(key) {
      foldchange_thresholds.push(key);
      
      });
      
    $('#threshold').attr('max', foldchange_thresholds.length-1);

  
   

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!doctype html>
<html>

<body>
    <!-- Display the sliding bar -->
    <input id="threshold" type="range"  min="0" max="1" step="1" value="0" />
    <br>

    <!-- Show foldchange threshold -->
    <div id="foldchange_threshold" style="display: inline-block; align:center;"></div>


</body>
</html>

正如您在脚本执行时发现的那样。滑动过程滞后,拖动后停止一段时间。如何平滑拖动过程?

1 个答案:

答案 0 :(得分:1)

我不确定它是否能解决任何问题,但是你可以通过不让jquery每次都找到元素来提高效率......

var $foldchange = $("#foldchange_threshold");
$('#threshold').change(function() {
  var thresholdIndex = parseInt($(this).val(), 10);
  $foldchange.html(foldchange_thresholds[thresholdIndex]);
});
根据OP的要求

更新 ...

$(function() {
  var foldchange_thresholds = [];
  var mydata = {"3":["c","d"], 
                "3.5":["j","k"], 
                "1.5":["a","b"], 
                "0.5":["c","d"], 
                "2.0":["e","f"], 
                "2.5":["x","y"] };
    
  Object.keys(mydata).sort().forEach(function(key) {
    foldchange_thresholds.push(key);
  });

  var $foldchange = $("#foldchange_threshold");
  $('#threshold').change(function() {
    var thresholdIndex = parseInt($(this).val(), 10);
    $foldchange.html(foldchange_thresholds[thresholdIndex]);
  }).attr('max', foldchange_thresholds.length-1);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!doctype html>
<html>

<body>
    <!-- Display the sliding bar -->
    <input id="threshold" type="range"  min="0" max="1" step="1" value="0" />
    <br>

    <!-- Show foldchange threshold -->
    <div id="foldchange_threshold" style="display: inline-block; align:center;"></div>
</body>
</html>