0

I am trying to use this script to freeze scrolling when an 'lightbox-style' image is opened. There's probably just a small error in the script but can't figure it out

jQuery.fn.lockToggle = function () { 

    var top = $(window).scrollTop();
    var left = $(window).scrollLeft();

    var clickCount = 0;

    $(this).click(function() {

        clickCount++;

        if(clickCount % 2 === 1  ){
            $('body').css('overflow', 'hidden');

            $(window).scroll(function(){
                $(this).scrollTop(top).scrollLeft(left);
            });

        } else {
           $('body').css('overflow', 'auto');
           $(window).unbind('scroll'); 
        }
    });

    return this;
};    

How this script works (in display order):

  1. Grabs the current scroll position and stores it in two variables
  2. Creates a variable for the number of clicks the object has
  3. If the click count is odd then it freezes the page in its current position
  4. Else (is even) then it allows the page to be freely scrolled

All of this works in a simple jQuery function that can be used just by calling .lockToggle()

You can view this in a full example here:

http://jsfiddle.net/JamesKyle/8H7hR/30/

(Click on the image)

4

1 回答 1

1

每次单击时,您都会绑定一个单击事件。这样每次绑定的事件越来越多,不会立即执行加锁。这似乎不是你想要的。

据我了解,您所指的错误是单击时滚动未锁定,再次单击时未解锁。您可以使用一个简单的isLocked变量正确实现这一点,如下所示:http: //jsfiddle.net/8H7hR/32/

var isLocked = false;

jQuery.fn.lockToggle = function () {    
    var top = $(window).scrollTop();
    var left = $(window).scrollLeft();

    if(isLocked) { // locked so unlock

       isLocked = false;
       $('body').css('overflow', 'auto');
       $(window).unbind('scroll');

    } else { // unlocked so lock

        isLocked = true;
        $('body').css('overflow', 'hidden');
        $(window).scroll(function(){
            $(this).scrollTop(top).scrollLeft(left);
        });

    }

    return this;
};
于 2011-11-21T18:55:55.920 回答