我试图在我的可滚动div中始终保持一个“幻灯片”。由于某种原因,脚本似乎将它略微偏离中心,我无法弄清楚原因。这是代码:
HTML:
<div id="carousel">
<div class="slide"><img src="http://placehold.it/300x150"/></div>
<div class="slide"><img src="http://placehold.it/300x150"/></div>
<div class="slide"><img src="http://placehold.it/300x150"/></div>
<div class="slide"><img src="http://placehold.it/300x150"/></div>
<div class="slide"><img src="http://placehold.it/300x150"/></div>
<div class="slide"><img src="http://placehold.it/300x150"/></div>
</div>
JavaScript(jQuery):
$(document).ready(function() {
// setup handlers
var carouselTimeout = null;
var scrollStop = function() {
var carousel = $('#carousel');
var carouselWidth = carousel.width();
var slideWidth = carousel.find('.slide:first-child').width();
var margin = carouselWidth / 20; // assumes margin of 5% on slides
var snapVal = slideWidth / 2 + margin;
var offset = carousel.scrollLeft();
slideNum = Math.round(offset / snapVal / 2);
var newOffset = slideNum * snapVal * 2;
carousel.animate({
scrollLeft: newOffset
});
};
$('#carousel').scroll(function() {
if (carouselTimeout) {
clearTimeout(carouselTimeout);
}
carouselTimeout = setTimeout(scrollStop, 500);
});
});
CSS:
#carousel {
width: 100%;
height: 150px;
background-color: rgba(0, 0, 0, 0.3);
overflow-x: scroll;
overflow-y: hidden;
white-space: nowrap;
}
#carousel .slide {
display: inline-block;
margin: 0 5%;
}
#carousel .slide:first-child {
margin: 0 5% 0 calc(50% - 150px);
}
#carousel .slide:last-child {
margin: 0 calc(50% - 150px) 0 5%;
}
答案 0 :(得分:2)
内联元素对代码中的空白区域很敏感。删除空格似乎可以解决问题:
<div id="carousel">
<div class="slide"><img src="http://placehold.it/300x150"/></div><div class="slide"><img src="http://placehold.it/300x150"/></div><div class="slide"><img src="http://placehold.it/300x150"/></div><div class="slide"><img src="http://placehold.it/300x150"/></div><div class="slide"><img src="http://placehold.it/300x150"/></div><div class="slide"><img src="http://placehold.it/300x150"/></div>
</div>
<强> jsFiddle example 强>
答案 1 :(得分:0)
inline-block
元素在其两侧都有空格。
有几种方法可以删除空格,例如在font-size: 0;
元素上设置#carousel
。 http://jsfiddle.net/5cp0unwj/3/
请参阅https://css-tricks.com/fighting-the-space-between-inline-block-elements/
更好的解决方案可能是使用flexbox
http://jsfiddle.net/5cp0unwj/6/