最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to trigger key combo with jQuery - Stack Overflow

programmeradmin9浏览0评论

I have coded some stuff:

/

I zoom in with .css("zoom") but I need the buttons to simulate CTRL + or CTRL -

This code isn't working for me:

e = jQuery.Event("keydown");        
e.which = 50;       
$("input").trigger(e);

Please help!

EDIT

I actually wanted to zoom-in and zoom-out the whole web page, not just a input field.

I have coded some stuff:

http://fincha.com/kunden/schmitt/

I zoom in with .css("zoom") but I need the buttons to simulate CTRL + or CTRL -

This code isn't working for me:

e = jQuery.Event("keydown");        
e.which = 50;       
$("input").trigger(e);

Please help!

EDIT

I actually wanted to zoom-in and zoom-out the whole web page, not just a input field.

Share Improve this question edited May 16, 2019 at 6:46 Abhishek Pandey 13.6k8 gold badges40 silver badges72 bronze badges asked Oct 8, 2010 at 18:43 Alexander_FAlexander_F 2,8773 gold badges29 silver badges62 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 12

jQuery normalizes modifier keys on events by setting one or more properties on the event object. So, you want to set event.ctrlKey to true, so this should work for you:

e = jQuery.Event("keydown");        
e.which = 50;
e.ctrlKey = true;
$("input").trigger(e);

However, as per a comment at source (linked below):

You cannot easily change values in the event object (probably for security reasons).

So, if you're unable to set the event's properties after constructing the Event object, then you can $.extend() it to set the ctrlKey property:

e = jQuery.Event("keydown");
fake = $.extend({}, e, {which: 50, ctrlKey: true});
$("input").trigger(fake);

One other thing: I'm not sure if you're trying to use key code 50 for the + or the - keys. Maybe you are, and you're using a different keyboard layout, but according to this demo, 50 is the JavaScript key code for hitting 2 - so that could also be part of your problem.


Source: comments on a jQuery API page.


Edit:

All this aside, I don't think you can actually change the browser's zoom level using JavaScript, even if you're "sending" the keyboard command to do so.

Access browser's page zoom controls with javascript

Source: http://www.scottklarr.com/topic/126/how-to-create-ctrl-key-shortcuts-in-javascript/

var isCtrl = false;

$(document).keyup(function (e) {
    if(e.which == 17) isCtrl=false;
}).keydown(function (e) {
    if(e.which == 17) isCtrl=true;
    if(e.which == 83 && isCtrl == true) {
        //run code for CTRL+S -- ie, save!
        return false;
    }
});

This is for Ctrl+s, but you should be able to modify it easily.

发布评论

评论列表(0)

  1. 暂无评论