jQuery scroll a div up and down using two buttons

后端 未结 4 2207
执念已碎
执念已碎 2021-02-10 13:45

I have a simple set of two buttons that when hovered should make a div move up and down to simulate a scrolling effect:

$(\"#down\").hover(function () {

    $(\         


        
相关标签:
4条回答
  • 2021-02-10 14:27
    1. You'll need to set the animations parameter to the divs actual height jQuery .height() method

    2. You should change your mouse events bindings on "mouseenter" and "mouseleave" and then with "mouseleave" you can stop a jQuery element animation with the jQuery .stop() method

    3. You can calculate this with the jQuery .height() method too.

    0 讨论(0)
  • 2021-02-10 14:34

    This code still need some debugging, but you can get the idea in it:

    $(document).ready(function() {
    
        if ($('.content').height() > $('.container').height()) {
            $("#down").hover(function () {
                animateContent("down");
            }, function() { $('.content').stop(); });
    
            $("#up").hover(function () {
                animateContent("up");
            }, function() { $('.content').stop(); });
        }
    });
    
    function animateContent(direction) {  
        var animationOffset = $('.container').height() - $('.content').height();
        if (direction == 'up') {
            animationOffset = 0;
        }
    
        $('.content').animate({ "marginTop": animationOffset + "px" }, "fast");
    }
    

    Code: http://jsfiddle.net/a89DF/6/

    0 讨论(0)
  • 2021-02-10 14:34

    I've written the jQuery plugin jquery.scrollbuttons which should fit your needs. It has a page on github and an examples page.

    The only thing the plugin will not do is to hide the button when scrolling is finished. If you still need this feature, I can easily add it.

    0 讨论(0)
  • 2021-02-10 14:43

    I think animate is more useful for single animation effects rather than a continuous and variable change. You can implement this yourself with an interval.

    var interval;
    
    $("#down").mouseenter(function () {
        interval = setInterval(ScrollDown, 100);
    });
    
    $("#down").mouseleave(function () {
        clearInterval(interval);
    });
    
    function ScrollDown() {
        $('.scroll').css("marginTop", "+=50px");
        // check bounds here to solve problem #1
    }
    
    /* do the same stuff for scrolling up */
    
    0 讨论(0)
提交回复
热议问题