Scroll div instead of page

2019-04-03 01:55发布

问题:

I have a lightbox of sorts on a website I am working on which acts like a "View Source" button. The background goes dark and the source appears but will only scroll if you have your mouse over that particular div (or in this case pre). I want to able to, for example, have my mouse in the top corner of the page and scroll down and I want the main lightbox to scroll. There's loads of code so I've used:

overflow-x: hidden;
overflow-y: scroll;

I'm sure it will require some JavaScript or jQuery, but I've no idea where to being.

It's in oporation on this page when you scroll down and click 'View Full Code'.

Any ideas?

回答1:

The most straight-forward way would be: http://jsfiddle.net/pimvdb/Ezvnp/3/.

$('body').bind('mousewheel', function(e) { // on scroll
    var $div = $('div');

    // set div scroll top offset to current + extra from this scroll
    $div.scrollTop($div.scrollTop() 
                    - e.originalEvent.wheelDelta);

    return false; // prevent body scrolling
});

To lock/unlock the scrolling, you could use a variable so as to only lock when that variable is true, e.g.: http://jsfiddle.net/pimvdb/Ezvnp/4/.

var locked = true;

$('body').bind('mousewheel', function(e) {
    if(locked) {
        var $div = $('div');

        $div.scrollTop($div.scrollTop() 
                        - e.originalEvent.wheelDelta);

        return false;
    }
});

$('button').click(function() {
    locked = !locked;
});