jQuery - How to get browser window to scroll horiz

2019-07-04 19:38发布

问题:

I have picture of an arrow in a div. This div is fixed in the bottom right corner of very wide page.

How can I use jQuery to scroll the window right 600px each time the div is clicked? (And is it possible to detect when the page can no longer scroll right, and hide the arrow?)

Cheers.

回答1:

Use the jquery method scrollLeft

$(document).ready(function(){
    $(window).scrollLeft((Number($(window).scrollLeft())+600)+'px');
});

Something like that :)



回答2:

Try something like this:

var distance = 600;
$("div").click(function() {
    $("html:not(:animated), body:not(:animated)").animate(
        {scrollLeft: "+="+distance}, 400
    );
});

jsfiddle here: http://jsfiddle.net/juXLu/2/

[edit] And here's detecting if you're at the end of the document http://jsfiddle.net/lukemartin/juXLu/5/

var distance = 600,
    docWidth = $(document).width(),
    scrollPos;

// click handler
$("div").click(function() {

    // animate 
    $("html:not(:animated), body:not(:animated)").animate(
        // amount to scroll
        {scrollLeft: "+=" + distance},
        // scroll speed (ms)
        400,
        // callback function
        function(){
            // check our scroll position
            scrollPos = $(window).width() + $(window).scrollLeft(); 
            // if it equals the doc width, we're at the end
            if(docWidth === scrollPos) {
                $("div").text("End of the line");
            }
        }
    );    

});


回答3:

You could user the Scrollto plugin,

http://plugins.jquery.com/project/ScrollTo

It is really easy to use, just use the documentation. Then you could create a placeholder to determine whether or not its to the end of the page. Just stick the placeholder at the very end, and calculate the distance.