imitate browser zoom with JavaScript

前端 未结 4 1279
慢半拍i
慢半拍i 2020-12-05 02:55

How is it possible to zoom out an entire document with JavaScript ?

My goal is to imitate the built-in browser zoom and zoom the entire document to 90%.

I ha

4条回答
  •  悲哀的现实
    2020-12-05 03:37

    Try using transform: scale(). Mozilla Docs

    .className {
        transform: scale(0.9)
    }
    

    You can change the scale amount with Javascript.

    let scaleAmount = 1 - 0.1
    document.body.style.transform = `scale(${scaleAmount})`
    

    scale() reduces or increases the width and height of an element. If you'd like the width to remain the original size, while all inner elements scale, the algorithm looks something like this:

    let scaleAmount = 1 - 0.1
    document.body.style.transform = `scale(${scaleAmount})`
    document.body.style.width = `${100 * (1 / scaleAmount)}%`
    document.body.style['transform-origin'] = `0 0`
    

    If you use a UI framework like React, you can pass the scaleAmount as it exists in the state to inline CSS.

    Example in React

提交回复
热议问题