javascript jQuery:水平滚动到 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19084152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: horizontal scroll to div
提问by user1374796
What I'm aiming to achieve in the end in something similar to the bbc site: http://www.bbc.co.ukwith a side scroll from section to section. Here's my code and I'll explain the problem I'm facing:
jsFiddle: http://jsfiddle.net/neal_fletcher/kzQFQ/2/
HTML:
我的最终目标是在类似于 bbc 站点的内容中实现:http://www.bbc.co.uk,并带有从一个部分到另一个部分的横向滚动。这是我的代码,我将解释我面临的问题:
jsFiddle:http: //jsfiddle.net/neal_fletcher/kzQFQ/2/
HTML:
<div class="wrapper">
<div class="container">
<div class="contentContainer red"></div>
<div class="contentContainer blue"></div>
<div class="contentContainer orange"></div>
</div>
</div>
<div class="left">LEFT</div>
<div class="right">RIGHT</div>
jQuery:
jQuery:
$(document).ready(function () {
$('.right').click(function () {
$('.container').animate({
'left': '-100%'
});
});
$('.left').click(function () {
$('.container').animate({
'left': '0%'
});
});
});
Firstly I don't know if it's possible to stack the .contentContainer
divs next to each other without having to set a 300% width on the .container
div. As the site is going to be CMS I don't want to keep changing the width of the .container
div to suit. There will only ever be one .contentContainer
div in view at one time too, thus I've set the overflow to hidden.
I can't seem to figure out a nice scroll function too, the one I have currently only scrolls the .container
div once by 100%, ideally I'd want this to work more like a slideshow, i.e. on a loop, if possible. Any suggestions would be greatly appreciated!
首先,我不知道是否可以将.contentContainer
div 彼此堆叠在一起,而不必在.container
div上设置 300% 的宽度。由于该站点将成为 CMS,我不想不断更改.container
div的宽度以适应。一次也只会有一个.contentContainer
div,因此我将溢出设置为隐藏。
我似乎也想不出一个很好的滚动功能,我目前只将.container
div滚动100% 一次,理想情况下,我希望它更像幻灯片,即循环播放,如果可能的话。任何建议将不胜感激!
回答by Thanos
I have updated your JSFiddle. With the code below you can count how many elements you got inside your slider and thereafter set the % width automatically.
我已经更新了你的JSFiddle。使用下面的代码,您可以计算滑块中的元素数量,然后自动设置 % 宽度。
var length = $('div .container').children('div .contentContainer').length;
$(".container").width(length*100 +'%');