简体   繁体   中英

Simulate a (Ctrl ) + (-) zoom out event using Javascript

How do we simulate a Ctrl - zoom out using Javascript? The style zoom property or the transform property seems to zoom out but differently with white space in the corners and not like how your typical Ctrl - zoom out on your browser would look like.

Through Javascript I tried the KeyboardEvent but it does not do the trick

var event = new KeyboardEvent("keypress", {key:"-", code:45 ,ctrlKey:true});
document.body.dispatchEvent(event);

Thanks.

I'm not sure if you're set on using Javascript, so I'll leave a CSS option for you here as well. CSS has an accessibility feature appropriately called Zoom which will do what you're asking.

div {
  zoom: 200%
}

As far as actually emulating the button press, though, try this;

  var event = jQuery.Event("keydown");
  event.which = 107;       // Key code for +
  event.ctrlkey = true;     
  $(document).trigger(event);

You are mis-using the key attribute. Use eg this instead:

var event = new KeyboardEvent('keydown', { key: 'Minus' });

Here's a link to the list of values for KeyboardEvent.key .

Try this:

    <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div style="text-align: center;">
        <h1>Result</h1>
        <button>Trigger Ctrl and - Keypress</button>
    </div>
    <script>
        let btn = document.querySelector("button");
        let result = document.querySelector("h1");

        // Normally keyboard pressed event
        document.body.addEventListener("keydown", (e) => {
            if (e.keyCode == 189 && e.ctrlKey) {
                result.innerText = "Ctrl Key and - key Pressed";
                ps();
            }
        });

        // Button event
        btn.addEventListener("click", () => {
            const keyEvent = new KeyboardEvent("keydown", {
                ctrlKey: true,
                keyCode: 189
            });
            document.body.dispatchEvent(keyEvent);
            ps();
        });

        const ps = () => {
            // back to previous state
            setTimeout(() => {
                result.innerHTML = "Result";
            }, 2000);
        }
    </script>
</body>
</html>

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