Вопрос

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)

Это было полезно?

Решение

You're binding a click event each time you click. This binds more and more events each time, and does not execute the locking immediately. This is not what you seem to want.

From my understanding, the error you're pointing at is the fact that the scrolling does not lock when clicking, and does not unlock when clicking again. You can implement this correctly with a simple isLocked variable as follows: 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;
};
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top