trigger multiple keypress to stimulate keyboard shortcut jquery

和自甴很熟 提交于 2019-12-11 08:09:48

问题


I want to create page zoom - according to keyboard shortcuts by jQuery. Mainly, I want to trigger Ctrl with + and Ctrl with - key pairs, when the user clicks on some element on the page. I have tried this code snippet from Way to trigger multiple keypress and hold events in jQuery question, but it does not work - it does not zoom the page

$("#zoom").click(function() {

    var e = $.Event("keydown");
    e.which = 61; // # key code for +
    e.ctrlKey = true;
    $(document).trigger(e);

});

回答1:


Your event trigger seems to work just fine, according to my fiddle.

$(document).bind('keydown', function(e) {
    e.preventDefault();

    var d = new Date();
    $('#log').html(
        'time: ' + d.getTime() + '<br/>' +
        'key: ' + e.which + '<br/>' +
        'ctrl: ' + (e.ctrlKey ? 'Yes' : 'No')
    );
});

However, you seem to be asking how to control the browser's zoom level, which isn't possible in most (if any) browsers without a plugin.

You could implement zooming of your own using CSS and Javascript, and even use the above snippet to capture Ctrl + and Ctrl - but you wouldn't be able to prevent the user zooming the page in other ways.

CSS:

    .text-zoom-0{
        font-size: .75em;
    }
    .text-zoom-1{
        font-size: 1em;
    }
    .text-zoom-2{
        font-size: 1.25em;
    }

Javascript:

jQuery(function($) {
    var currentZoom = 1,
        minZoom = 0,
        maxZoom = 2,
        changeZoom = function(increase) {
            var newZoom = currentZoom;

            if (increase && currentZoom < maxZoom) {
                newZoom++;
                $('.text-zoom-' + currentZoom)
                    .addClass('.text-zoom-' + newZoom)
                    .removeClass('.text-zoom-' + currentZoom);
            } else if (currentZoom > minZoom) {
                newZoom--;
                $('.text-zoom-' + currentZoom)
                    .addClass('.text-zoom-' + newZoom)
                    .removeClass('.text-zoom-' + currentZoom);
            }

            currentZoom = newZoom;
        };

    $('.zoomIn').click(function(e) {
        changeZoom(true);
    });

    $('.zoomOut').click(function(e) {
        changeZoom(false);
    });
});

And of course you'd have to do the same for images, navigation, and every other element on the page. If you wanted to actually do this, you could be much more clever about the CSS than this little snippet, but remember, could is not the same as should by any stretch of the imagination...




回答2:


You can use this librarie. there are a lot of examples

http://www.openjs.com/scripts/events/keyboard_shortcuts/



来源:https://stackoverflow.com/questions/13442457/trigger-multiple-keypress-to-stimulate-keyboard-shortcut-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!