如何阻止 jquery UI 滑块滑出容器

How do I stop the jquery UI slider from sliding beyond the container

我正在使用 jQuery UI 水平滑块。我需要手柄的位置始终在滑块内。如果我将 margin-left 设置为句柄宽度的负值,则右侧位置在容器内,但左侧位置移出容器。我只想用 CSS 来实现。我不想添加任何包装器 div.
以下是HTML代码:

<div id="slider"></div>
<ul id="box">
  <li>Fade with the above slider...</li>
  <li>Fade with the above slider...</li>
</ul>

CSS如下:

#box {
  width: 200px;
  height: 200px;
  background-color: #ff0000;
}

#slider {
  width: 200px;
}

.ui-slider .ui-slider-handle {
  width: 20px;
  margin-left: -10px;
}

最后是js代码:

$(document).ready(function() {
 $('#slider').slider({
   min: 0,
   max: 1,
   step: 0.1,
   value: 1
 })
 .bind("slide", function() {
   //get the value of the slider with this call
   var o = $(this).slider('value');
   $(e).css('opacity', o)
 });
});

我们将不胜感激。

首先,最好的方法是不更改它。只需稍微缩小滑块,使其适合带手柄的区域。

无论如何,如果你想在相应的边而不是它的中心停止标记在 0 和 100%,你可以这样做:

.ui-slider-handle[style*="left: 0"] {
  margin-left: -1px;
}

.ui-slider-handle[style*="left: 100"] {
  margin-left: -1.2em;
}

$("div").slider();
section {
  margin: 1em;
  border: 1px dotted red;
}

h1 {
  margin: 0;
}

div {
  margin: .3em .6em;
}

.new .ui-slider:before {
  content: "";
  background: inherit;
  border: inherit;
  border-radius: inherit;
  position: absolute;
  left: -.6em; /* Half of the handle width */
  top: -1px; /* Width of the border */
  right: -.6em;
  bottom: -1px;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

<section>
  <h1>Default</h1>
  <div></div>
</section>

<section class="new">
  <h1>Modified</h1>
  <div></div>
</section>