我正在动态制作图像滑块(不想使用任何hard corded值)。我可以制作滑块,但我有两个问题。
为什么我需要20px更多的ul宽度。有没有办法不使用这个硬线值。

 $('#list').css('width',$('#list').find('.box').length*li_Width+20)

当用户单击left按钮时,为什么框的某些部分next。例如当用户单击next按钮时,它显示next框而不显示任何部分(绿色框)…但是当用户单击下一个按钮时,它显示blue框的某些部分为什么?为什么不完全滑动?如果用户再次点击下一步按钮,它会再次显示红色的更多部分为什么?
这是我的密码
https://plnkr.co/edit/t2yOFkO1QBWOVLFreiXm?p=preview
//这里有密码
$(function(){

  var li_Width =$('#list').find('.box:first').outerWidth(true);
  // why 20 pixel is hardcorded
  $('#list').css('width',$('#list').find('.box').length*li_Width+20)
 $('#next').click(function(){
  $('#list').css('margin-left',addToMarginLeft($('#list'),-li_Width))
 })
 $('#pre').click(function(){
    $('#list').css('margin-left',addToMarginLeft($('#list'),li_Width))
 })

 function addToMarginLeft(elem, pixels) {
    var ml = parseFloat(elem.css('margin-left'));
    elem.animate({
    'margin-left': (ml + pixels) + 'px'
    },1000)

  }

})

最佳答案

我认为这是由于cssinline-block元素之间的空白造成的。
这会造成一些额外的空间,所以你必须增加20像素。
有几种方法可以解决这最后一个问题:在li之间生成,或者像下面这样将字体大小设置为0:

ul {
  ...
  font-size: 0
}

下面是工作片段:
我刚刚添加了一些jquery代码,以防止在最后一个周年纪念日完成之前触发另一个周年纪念日的miltiple click按钮:
// Code goes here
$(function() {

  var li_Width = $('#list').find('.box:first').outerWidth(true);
  // 20 px removed !!!
  $('#list').css('width', $('#list').find('.box').length * li_Width)

  $('#next').click(function() {
    if( !$("#list").is(":animated") )
    $('#list').css('margin-left', addToMarginLeft($('#list'), -li_Width))
  })
  $('#pre').click(function() {
    if( !$("#list").is(":animated") )
    $('#list').css('margin-left', addToMarginLeft($('#list'), li_Width))
  })

  function addToMarginLeft(elem, pixels) {
    var ml = parseFloat(elem.css('margin-left'));
    elem.animate({
      'margin-left': (ml + pixels) + 'px'
    }, 1000)

  }

})

/* Styles go here */

.box {
  width: 100px;
  height: 100px;
}

body {
  margin: 0px;
  padding: 0px;
}

.green {
  background-color: green;
}

.red {
  background-color: red;
}

.pink {
  background-color: pink;
}

.yellow {
  background-color: yellow;
}

.blue {
  background-color: blue;
}

.orange {
  background-color: orange;
}

ul {
  list-style: none;
  padding: 0px;
  margin: 0px;
  width: 1300px;
  /* here you set font to 0 for extra space */
  font-size: 0
}

li {
  display: inline-block;
  margin-left: 15px;
  padding: 0;
}

#container {
  width: 300px;
  margin: 0 auto 0 auto;
  overflow: hidden;
}

#list {
  border: 1px solid black;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <button id="next">next</button>
  <button id="pre">pre</button>
  <ul id="list">
    <li class="box green">
    </li>
    <li class="box blue">
    </li>
    <li class="box red">
    </li>
    <li class="box yellow">
    </li>
    <li class="box pink">
    </li>
    <li class="box orange">
    </li>
  </ul>
</div>

09-30 16:23
查看更多