Override browsers CTRL+(WHEEL)SCROLL with javascript

前端 未结 3 738
情话喂你
情话喂你 2021-01-04 17:58

In most browsers on linux, CTRL+(WHEEL)SCROLL allows the user to zoom in and out of the page by enlarging or shrinking the size of all elements. Now I want to ove

3条回答
  •  春和景丽
    2021-01-04 18:40

    There are a lot of difficulties in a question like this. Basically, there are two steps:

    1. Listen for the keydown and keyup events, and keep track of when Ctrl is down
    2. Listen for the mouse wheel, and (if Ctrl is down) do what you want

    But here are the problems you have to address:

    • How are you going to apply the event listeners/handlers?
    • According to QuirksMode, browsers on Mac don't return an accurate keycode for Ctrl.
    • Also according to QuirksMode, Firefox doesn't support the mousewheel event. You'll have to use DOMMouseScroll instead.
    • According to the MDC, there are some instances where the DOMMouseScroll event, when used with Ctrl, never even gets fired!

    I'm not saying they're insurmountable, or even that they're big problems. Using a good JavaScript library should abstract away most of them, if not all. Being selective in your choice of browsers/OSs to support will also help quite a bit, if that's doable.

    If I were to do this with jQuery (and a jQuery mousewheel plugin), it would look something like this:

    (function ($) {
        var isCtrl = false;
    
        function ctrlCheck(e) {
            if (e.which === 17) {
                isCtrl = e.type === 'keydown' ? true : false;
            }
        }
    
        function wheelCheck(e, delta) {
            // `delta` will be the distance that the page would have scrolled;
            // might be useful for increasing the SVG size, might not
            if (isCtrl) {
                e.preventDefault();
                yourResizeMethod(delta);
            }
        }
    
        $(document).
            keydown(ctrlCheck).
            keyup(ctrlCheck).
            mousewheel(wheelCheck);
    }(jQuery));
    

提交回复
热议问题