简体   繁体   中英

Disable element scrolling with keyboard arrows

Fiddle

So I'm trying to disable scrolling of a div when another div is visible.

The code bellow I'm using does just that, but only when using mousewheel to scroll.

If I click the scrollbar and drag it, or if I focus the div and use keyboard down button, the scrolling still happens.

Why is that and how can I solve my problem (possibly without overlaying a transparent element over my scrollbar or similar "hacks")?

$('#element').on('scroll mousewheel keydown keypress keyup', function (event) {
    const element = $(event.currentTarget);
    const shouldScroll = false;

    if (!shouldScroll) {
        event.preventDefault();
        event.stopPropagation();
        return false;   
    }
});

Why don't you do it like this?

 var scrollEnabled = true; var scrollX = 0; var scrollY = 0; $(document).ready(function() { $('div.outer').on('scroll', function(event) { if (!scrollEnabled) this.scrollTo(scrollX, scrollY); }); $('#tglBtn').on('click', function(event) { if (scrollEnabled == true) { scrollEnabled = false; scrollX = $('div.outer').scrollLeft(); scrollY = $('div.outer').scrollTop(); } else { scrollEnabled = true; } }); });
 div.outer { height: 500px; width: 500px; background-color: red; overflow-y: scroll; } div.inner { height: 200px; width: 500px; } div.inner:nth-child(odd) { background: blue; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="button" id="tglBtn" value="Enable/Disable scrolling" /> <div class="outer"> <div class="inner"> </div> <div class="inner"> </div> <div class="inner"> </div> <div class="inner"> </div> <div class="inner"> </div> <div class="inner"> </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM