问题描述:

I'm trying to use the left variable to replace '1493' in this code. It works fine when it's a number but when I changed it over to use 'left' the if statement stops working.

$(document).scroll(function () {

var width = $(document).width();

var left = $(document).scrollLeft();

var postCount = $(".post").length;

var columnLength = ( width - ((postCount*743) - 1493)) - (width-(postCount*743));

if(left >= columnLength) {

$(".num").text(left);

}

});

Does anyone have any ideas where I'm going wrong with this? Any pointers would be great.

网友答案:

You may need to force it to be an integer:

var left = parseInt($(document).scrollLeft()); 
网友答案:

Lets take a look at the math you have really quick.

var columnLength = ( width - ((postCount*743) - 1493)) - (width-(postCount*743));

You are basically cancelling out width, and (postCount*743). It leaves you with --1493 which is positive 1493. The following would have the same effect:

var columnLength = 1493;

So, the reason the if statement fires when you put in the static value 1493, is because columnLength ALWAYS equals 1493 which, of course satisfies this condition:

if (1493 >= columnLength)

You could as easily write:

if (1493 >= 1493)

That said, it should still, theoretically fire when left becomes greater than or equal to 1493. But left is the current horizontal scroll position in pixels. It would be a HUGELY wide page to hit a scroll position of 1493.

Edit: Here's a fiddle to give an idea of how fast the scroll position increases: http://jsfiddle.net/vdQ7B/16/

EDIT 2:

Here is an update in response to your comment.

As I understand it, you were trying to get a horizontal scrollbar that would, essentially, scroll forever.

Please see the following fiddle for a demo: http://jsfiddle.net/vdQ7B/40/

The code is below:

$(document).scroll(function () { 
    var width = $(document).width();
    var left = $(document).scrollLeft();
    var viewportwidth = window.innerWidth;

    // If our scrollbar gets to the end, 
    // add 50 more pixels. This could be set
    // to anything.
    if((left + viewportwidth) === width) {
        $("body").css("width", width + 50);
    } 
 });

Per the comments in the code, we simply increase the width of the body if we determine we've reached the end. scrollLeft() will only tell us the number of pixels that are currently not visible to the left of the viewable area. So, we need to know how much viewable area we have, and how much is hidden to the left to know if we've scrolled all the way to the end.

If you have a scroll bar on an inner element, like a div, you'd need to update with width of the div, not the body.

Note: You may also need to use $(window) instead of $(document) to get scrollLeft() to work across all browsers.

Note: See here about using "innerWidth". There are some compatibility issues, and you may need to expand it a bit to handle other cases (IE6).

相关阅读:
Top