Auto-Scroll div horizontally to the very end with overflow-y set to scroll (jQuery)

吃可爱长大的小学妹 提交于 2019-12-22 01:32:15

问题


I am using this jQuery script that automatically scrolls a div horizontally based on the width of the div. But I need it to scroll to the very end of the div based on the end of the content that is inside of the div. The div has an 'overflow-y: scroll' attribute, so I'd like it to scroll through all of the content until it reaches the end.

This is the script I'm currently using:

function animatethis(targetElement, speed) {
    var width = $(targetElement).width();
    $(targetElement).animate({ marginLeft: "-="+width},
    {
        duration: speed,
        complete: function ()
        {
            targetElement.animate({ marginLeft: "+="+width },
            {
                duration: speed,
                complete: function ()
                {
                    animatethis(targetElement, speed);
                }
            });
        }
    });
};
animatethis($('#q1'), 5000);

It does scroll, but it's not scrolling to the very end of the content inside of the div. Here is a jFiddle that shows what I mean: http://jsfiddle.net/rKu6Y/535/

How can I get it to auto-scroll horizontally to the END of the content rather than just the width of the div?

I hope this all makes sense. Thanks.


回答1:


You can animate the scrollLeft property, using scrollWidth and clientWidth:

function animatethis(targetElement, speed) {
    var scrollWidth = $(targetElement).get(0).scrollWidth;
    var clientWidth = $(targetElement).get(0).clientWidth;
    $(targetElement).animate({ scrollLeft: scrollWidth - clientWidth },
    {
        duration: speed,
        complete: function () {
            targetElement.animate({ scrollLeft: 0 },
            {
                duration: speed,
                complete: function () {
                    animatethis(targetElement, speed);
                }
            });
        }
    });
};
animatethis($('#q1'), 5000);

The result can be seen in this jsfiddle.



来源:https://stackoverflow.com/questions/39337646/auto-scroll-div-horizontally-to-the-very-end-with-overflow-y-set-to-scroll-jque

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!