我想保持一個「幻燈片」在我的可滾動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%;
}
什麼是 「輕微」 呢?這可能是一個'內聯塊/空白'問題? –
@Paulie_D它可能是,但我認爲它可能是頁面寬度依賴意味着它更像是一個像素分割問題。儘管如果你看到一個可能的空白問題,隨意玩它。 – carloabelli
這殺死了空白:http://jsfiddle.net/5cp0unwj/1/和對我來說,第一個和最後一個塊都完全居中 – Marcel