【问题标题】:Slider handle needs to restricted inside the container, should not go beyond the container滑块手柄需限制在容器内,不得超出容器
【发布时间】:2018-08-28 21:32:07
【问题描述】:

在我创建的自定义滑块中,手柄超出了容器。但我希望它保持在容器限制内。我们可以通过在 CSS 中将 margin-left 设置为偏移量来简单地做到这一点。但我的要求是当手柄右端检测到容器的末端时,不应再允许手柄移动。任何帮助表示赞赏。谢谢。

演示链接:https://jsfiddle.net/mohanravi/1pbzdyyd/30/

document.getElementsByClassName('contain')[0].addEventListener("mousedown", downHandle);

function downHandle() {
  document.addEventListener("mousemove", moveHandle);
  document.addEventListener("mouseup", upHandle);
}

function moveHandle(e) {
  var left = e.clientX - document.getElementsByClassName('contain')[0].getBoundingClientRect().left;
  var num = document.getElementsByClassName('contain')[0].offsetWidth / 100;
  var val = (left / num);

  if (val < 0) {
    val = 0;
  } else if (val > 100) {
    val = 100;
  }

  var pos = document.getElementsByClassName('contain')[0].getBoundingClientRect().width * (val / 100);

  document.getElementsByClassName('bar')[0].style.left = pos + 'px';
}

function upHandle() {
  document.removeEventListener("mousemove", moveHandle);
  document.removeEventListener("mouseup", upHandle);
}
.contain {
  height: 4px;
  width: 450px;
  background: grey;
  position: relative;
  top: 50px;
  left: 40px;
}

.bar {
  width: 90px;
  height: 12px;
  background: transparent;
	border: 1px solid red;
  position: absolute;
  top: calc(50% - 7px);
  left: 0px;
  cursor: ew-resize;
}
<div class='contain'>
  <div class='bar'></div>
</div>

【问题讨论】:

  • 如果要选择单个元素,请使用querySelector,这就是它的用途-使用返回集合的方法(例如getElementsByClassName)然后选择集合中的第一个元素并不好.
  • this更新小提琴

标签: javascript jquery html css slider


【解决方案1】:

你需要改变 这个

document.getElementsByClassName('bar')[0].style.left = pos + 'px';

到这里

if(pos > 90){
  document.getElementsByClassName('bar')[0].style.left = pos - 90 + 'px';
  }
  else{
  document.getElementsByClassName('bar')[0].style.left = 0 + 'px';
  }

因为你的条的宽度是 90 像素,所以我减去 90。

this updated fiddle

【讨论】:

  • 因为左右边框也需要算入2px,或者使用.bar {box-sizing: border-box}
  • @VXp 是的。抱歉没有注意到。但是可以使用 box-sizing
猜你喜欢
  • 1970-01-01
  • 2018-10-13
  • 2017-09-12
  • 2018-11-01
  • 2018-03-30
  • 1970-01-01
  • 1970-01-01
  • 2021-12-02
  • 1970-01-01
相关资源
最近更新 更多