简体   繁体   English

如何使用jQuery动画容器中的元素?

[英]How to animate through elements in a container using jQuery?

I'm working on an article carousel using jQuery to try and get a better hold on the framework. 我正在使用jQuery开发一篇文章轮播,试图更好地掌握框架。 I've got a containing div and in this div I have multiple articles. 我有一个包含div,在这个div我有多篇文章。

<div id="container">
    <article>
        <h3>Article Heading</h3>
        <p>Article Content</p>
    </article>
    <article>
    ...
</div>

The div is formatted to be a specific width and height and overflow is set to hidden div被格式化为特定的宽度和高度,溢出被设置为隐藏

I'm trying to animate it so when the user clicks a button, it calls the function to scroll to either the next or previous article 我正在尝试设置动画,以便当用户单击按钮时,它会调用该函数滚动到下一篇或上一篇文章

var articles = -1;
var currentPosition = -1;
window.onload = function(){
    articles = $("#container>article");
    currentPosition = 0;
}
function scrollNext(){
    $('#container').animate({
        scrollTop: $(articles[currentPosition+1]).offset().top
    }, 750);
    currentPosition++;
}

However, when the scrollNext function is called, it will scroll to the paragraph of the next article, or will scroll out of order. 但是,当调用scrollNext函数时,它将滚动到下一篇文章的段落,或者将无序滚动。

I'm wondering if this is an issue with a selector, or possibly my styling of the page, or what the proper way of doing this would be. 我想知道这是选择器的问题,还是我的页面样式,或者这样做的正确方法。 See the full page here 请在此处查看整页

Or try it out on jsfiddle 或者在jsfiddle上尝试一下

Your margins are messing you up. 你的利润让你搞砸了。 Why not try something like this? 为什么不尝试这样的事情呢?

var box = $("#container"), height = box.height();
currentPosition++;
box.animate({scrollTop: currentPosition*height});

You are using .offset() which gives you the offset compared to the body. 您正在使用.offset() ,它为您提供与正文相比的偏移量。

Since you are wanting to scroll inside the div#container you need to use .position() 因为你想要在div#container内滚动你需要使用.position()

http://api.jquery.com/position/ http://api.jquery.com/position/

And using position() requires that the div #container be position: relative; 并且使用position()要求div #containerposition: relative; in your css. 在你的CSS。

Once you have that in your jQuery you need to change your scrollTop animations to include the scrollTop() of the div#container added to the position() of the next article 一旦你在jQuery中拥有它,你需要更改你的scrollTop动画,以包括div#containerscrollTop()添加到下一篇文章的position()

like so: 像这样:

$('#container').animate({
  scrollTop: $('#container').scrollTop() + $(pdiv).position().top
}, 750);

You can see it all working in your updated jsfiddle: 您可以在更新的jsfiddle中看到它全部工作:

http://jsfiddle.net/9ryjy/1/ http://jsfiddle.net/9ryjy/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM