使用Javascript + Input type=range滚动Div

Scroll a Div using Javascript + Input type=range

本文关键字:range 滚动 Div type Javascript Input 使用      更新时间:2023-09-26

我目前正在研究一个项目,我必须根据输入类型=范围的移动滚动某个部分。这是代码-

$('input[type=range]').val('0');
$('input[type=range]').on('change input', function() {
	var max = 60;
	var value = $(this).val();
	var percent = value / max;
  var height = $('.tooltip').height();
  console.log("v",value);
var top = value + "%";
  console.log("t",top);
	$('.tooltip').css('top', top);
})
.tooltip {
  position: absolute;
  left: 0;
  background: silver;
  border-left: dotted 2px orange;
  padding: 2px;
  max-width: 200px;
  text-align: center;
}
input[type=range] {
  margin-top: 50px;
  width: 100%;
}
input[type=range]::-webkit-slider-thumb:after {
  content: '';
  width: 100px;
  background: transparent;
  color: #000;
  border-left: dotted 2px orange;
  pointer-events: none;
  padding: 50px;
  position: relative;
  top: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height:250px;position:relative;border:2px solid;width:200px;overflow:hidden;">
<div class="tooltip">
  <p>How can I get this border to <em>consistently</em> align with the one on the thumb?</p>
</div>
</div>
<input type="range" min="0" max="100"/>

-这是工作。但问题是,一旦我滚动到100%,滚动div超出了外部div。我希望滚动div在外部div结束时停止,即使范围是在100%(滚动div不应该越过外部div)。

  1. 将javascript部分的max def更改为100,因为输入已经定义了max="100"。
  2. 使用高差代替高度

$('input[type=range]').val('0');
$('input[type=range]').on('change input', function() {
  var max = 100;
  var value = $(this).val();
  var percent = value / max;
  var parent_height = $('.tooltip').parent().height();
  var height = $('.tooltip').height();
  //console.log("p:" + parent_height + " s:" + height + " %:" + percent);
  var top = (parent_height - height) * percent;
  //console.log("t", top, "h", parent_height - height);  
  if(percent <= 1)
    $('.tooltip').css('top', top + "px");
})
.tooltip {
  position: absolute;
  left: 0;
  background: silver;
  border-left: dotted 2px orange;
  padding: 2px;
  max-width: 200px;
  text-align: center;
}
input[type=range] {
  margin-top: 50px;
  width: 100%;
}
input[type=range]::-webkit-slider-thumb:after {
  content: '';
  width: 100px;
  background: transparent;
  color: #000;
  border-left: dotted 2px orange;
  pointer-events: none;
  padding: 50px;
  position: relative;
  top: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height:250px;position:relative;border:2px solid;width:200px;overflow:hidden;">
  <div class="tooltip">
    <p>How can I get this border to <em>consistently</em> align with the one on the thumb?</p>
  </div>
</div>
<input type="range" min="0" max="100" />

div左侧设置前需要添加条件

var tooltipWidth = $('.tooltip').width();
if(left + tooltipWidth > width){
    left = width - tooltipWidth;
}