简体   繁体   中英

AutoScroll div content both ways

I want to make a div autoscroll it's content. The content height is variable. Here is what I managed to work out, but if I set the height to .childElement.outerHeight or height, it will only scroll 78px, I don't know why.

 var element = jQuery('#content');
            setInterval(scrollDown(element), 1000)

        function scrollDown(element) {
            var childElement = element.children();
            scrollAmount = childElement.outerHeight();
            element.animate({ scrollTop: 1000 }, 3000, null, scrollUp(childElement));
        }
        function scrollUp(element) {
            element.animate({ scrollTop: 0 }, 500);
        }

        });

Any help is highly appreciated.

Thanks, Sebastian

I've found the solution.

The main problem is that I used document.ready , and the div's child element did not have all the items in it so the scroll height was not correct. I've changed that with window.load and made some changes to the scroll animation. Also the parameters were wrong on the animate function.

Here is the final, working properly snippet.

jQuery(window).load(function () {
    var element = jQuery('#content');
    var childElement = element.children();
    var scrollAmount = childElement.height();
    var speedDown = scrollAmount * 20;
    var speedUp = speedDown * 0.3;

    scrollDown(element, scrollAmount, speedUp, speedDown);

    function scrollDown(element, scrollAmount, speedUp, speedDown) {

        element.animate({ scrollTop: scrollAmount }, speedDown, function () {
            element.animate({ scrollTop: scrollAmount * -1 }, speedUp);
            scrollDown(element, scrollAmount, speedUp, speedDown);
        });
    }
})

Try this on small, I've had a little line in your code for auto scrollUp and Down non-stop without mouseover timeout stop:

jQuery(window).load(function () {
  var element = jQuery('#content');
  var childElement = element.children();
  var scrollAmount = childElement.height();
  var speedDown = scrollAmount * 50;
  var speedUp = speedDown * 0.9;

  scrollDown(element, scrollAmount, speedUp, speedDown);

  function scrollDown(element, scrollAmount, speedUp, speedDown) {

    element.animate({ scrollTop: scrollAmount }, speedDown, function () {
        element.animate({ scrollTop: scrollAmount * +3 }, speedUp);
        scrollDown(element, scrollAmount, speedUp, speedDown);
        element.animate({ scrollTop: scrollAmount * -3 }, speedDown);
    });
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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