更改浏览器缩放级别

发布于 2024-07-25 05:16:52 字数 110 浏览 2 评论 0原文

我需要在我的网站上创建 2 个按钮来更改浏览器缩放级别 (+) (-)。 由于图像大小和布局问题,我请求浏览器缩放而不是 css 缩放。

嗯,这可能吗? 我听到了相互矛盾的报道。

I have need to create 2 buttons on my site that would change the browser zoom level (+) (-). I'm requesting browser zoom and not css zoom because of image size and layout issues.

Well, is this even possible? I've heard conflicting reports.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

江城子 2024-08-01 05:16:52

尽管在 Firefox 中不起作用,但在 IE 和 chrome 中可以使用:

<script>
   function toggleZoomScreen() {
       document.body.style.zoom = "80%";
   } 
</script>

<img src="example.jpg" alt="example" onclick="toggleZoomScreen()">

Possible in IE and chrome although it does not work in firefox:

<script>
   function toggleZoomScreen() {
       document.body.style.zoom = "80%";
   } 
</script>

<img src="example.jpg" alt="example" onclick="toggleZoomScreen()">
南城追梦 2024-08-01 05:16:52

我想说在大多数浏览器中这是不可能的,至少在没有一些额外的插件的情况下是不可能的。 无论如何,我会尽量避免依赖浏览器的缩放,因为实现各不相同(某些浏览器仅缩放字体,其他浏览器也缩放图像等)。 除非你不太关心用户体验。

如果您需要更可靠的缩放,请考虑使用 JavaScript 和 CSS 或可能在服务器端缩放页面字体和图像。 图像和布局缩放问题可以通过这种方式解决。 当然,这需要做更多的工作。

I would say not possible in most browsers, at least not without some additional plugins. And in any case I would try to avoid relying on the browser's zoom as the implementations vary (some browsers only zoom the fonts, others zoom the images, too etc). Unless you don't care much about user experience.

If you need a more reliable zoom, then consider zooming the page fonts and images with JavaScript and CSS, or possibly on the server side. The image and layout scaling issues could be addressed this way. Of course, this requires a bit more work.

迷鸟归林 2024-08-01 05:16:52

尝试一下这是否适合您。 这适用于 FF、IE8+ 和 Chrome。 else 部分适用于非 Firefox 浏览器。 尽管这为您提供了缩放效果,但它实际上并没有在浏览器级别修改缩放值。

    var currFFZoom = 1;
    var currIEZoom = 100;

    $('#plusBtn').on('click',function(){
        if ($.browser.mozilla){
            var step = 0.02;
            currFFZoom += step; 
            $('body').css('MozTransform','scale(' + currFFZoom + ')');
        } else {
            var step = 2;
            currIEZoom += step;
            $('body').css('zoom', ' ' + currIEZoom + '%');
        }
    });

    $('#minusBtn').on('click',function(){
        if ($.browser.mozilla){
            var step = 0.02;
            currFFZoom -= step;                 
            $('body').css('MozTransform','scale(' + currFFZoom + ')');

        } else {
            var step = 2;
            currIEZoom -= step;
            $('body').css('zoom', ' ' + currIEZoom + '%');
        }
    });

Try if this works for you. This works on FF, IE8+ and chrome. The else part applies for non-firefox browsers. Though this gives you a zoom effect, it does not actually modify the zoom value at browser level.

    var currFFZoom = 1;
    var currIEZoom = 100;

    $('#plusBtn').on('click',function(){
        if ($.browser.mozilla){
            var step = 0.02;
            currFFZoom += step; 
            $('body').css('MozTransform','scale(' + currFFZoom + ')');
        } else {
            var step = 2;
            currIEZoom += step;
            $('body').css('zoom', ' ' + currIEZoom + '%');
        }
    });

    $('#minusBtn').on('click',function(){
        if ($.browser.mozilla){
            var step = 0.02;
            currFFZoom -= step;                 
            $('body').css('MozTransform','scale(' + currFFZoom + ')');

        } else {
            var step = 2;
            currIEZoom -= step;
            $('body').css('zoom', ' ' + currIEZoom + '%');
        }
    });
等待圉鍢 2024-08-01 05:16:52

您可以使用 CSS3 缩放功能,但我还没有使用 jQuery 对其进行测试。 现在就尝试并让您知道。
更新:测试过,有效,但很有趣

You can use the CSS3 zoom function, but I have not tested it yet with jQuery. Will try now and let you know.
UPDATE: tested it, works but it's fun

鸵鸟症 2024-08-01 05:16:52

我找不到更改实际浏览器缩放级别的方法,但您可以使用 CSS 变换:scale() 来非常接近。 这是我基于 JavaScript 和 jQuery 的解决方案:

<!-- Trigger -->
<ul id="zoom_triggers">
    <li><a id="zoom_in">zoom in</a></li>
    <li><a id="zoom_out">zoom out</a></li>
    <li><a id="zoom_reset">reset zoom</a></li>
</ul>

<script>
    jQuery(document).ready(function($)
    {
        // Set initial zoom level
        var zoom_level=100;

        // Click events
        $('#zoom_in').click(function() { zoom_page(10, $(this)) });
        $('#zoom_out').click(function() { zoom_page(-10, $(this)) });
        $('#zoom_reset').click(function() { zoom_page(0, $(this)) });

        // Zoom function
        function zoom_page(step, trigger)
        {
            // Zoom just to steps in or out
            if(zoom_level>=120 && step>0 || zoom_level<=80 && step<0) return;

            // Set / reset zoom
            if(step==0) zoom_level=100;
            else zoom_level=zoom_level+step;

            // Set page zoom via CSS
            $('body').css({
                transform: 'scale('+(zoom_level/100)+')', // set zoom
                transformOrigin: '50% 0' // set transform scale base
            });

            // Adjust page to zoom width
            if(zoom_level>100) $('body').css({ width: (zoom_level*1.2)+'%' });
            else $('body').css({ width: '100%' });

            // Activate / deaktivate trigger (use CSS to make them look different)
            if(zoom_level>=120 || zoom_level<=80) trigger.addClass('disabled');
            else trigger.parents('ul').find('.disabled').removeClass('disabled');
            if(zoom_level!=100) $('#zoom_reset').removeClass('disabled');
            else $('#zoom_reset').addClass('disabled');
        }
    });
</script>

I could't find a way to change the actual browser zoom level, but you can get pretty close with CSS transform: scale(). Here is my solution based on JavaScript and jQuery:

<!-- Trigger -->
<ul id="zoom_triggers">
    <li><a id="zoom_in">zoom in</a></li>
    <li><a id="zoom_out">zoom out</a></li>
    <li><a id="zoom_reset">reset zoom</a></li>
</ul>

<script>
    jQuery(document).ready(function($)
    {
        // Set initial zoom level
        var zoom_level=100;

        // Click events
        $('#zoom_in').click(function() { zoom_page(10, $(this)) });
        $('#zoom_out').click(function() { zoom_page(-10, $(this)) });
        $('#zoom_reset').click(function() { zoom_page(0, $(this)) });

        // Zoom function
        function zoom_page(step, trigger)
        {
            // Zoom just to steps in or out
            if(zoom_level>=120 && step>0 || zoom_level<=80 && step<0) return;

            // Set / reset zoom
            if(step==0) zoom_level=100;
            else zoom_level=zoom_level+step;

            // Set page zoom via CSS
            $('body').css({
                transform: 'scale('+(zoom_level/100)+')', // set zoom
                transformOrigin: '50% 0' // set transform scale base
            });

            // Adjust page to zoom width
            if(zoom_level>100) $('body').css({ width: (zoom_level*1.2)+'%' });
            else $('body').css({ width: '100%' });

            // Activate / deaktivate trigger (use CSS to make them look different)
            if(zoom_level>=120 || zoom_level<=80) trigger.addClass('disabled');
            else trigger.parents('ul').find('.disabled').removeClass('disabled');
            if(zoom_level!=100) $('#zoom_reset').removeClass('disabled');
            else $('#zoom_reset').addClass('disabled');
        }
    });
</script>
梦醒灬来后我 2024-08-01 05:16:52

正如接受的答案提到的,您可以将DOM中元素的fontSize css属性一一放大,以下代码供您参考。

 <script>
    var factor = 1.2;
    var all = document.getElementsByTagName("*");
    for (var i=0, max=all.length; i < max; i++) {
        var style = window.getComputedStyle(all[i]);
        var fontSize = style.getPropertyValue('font-size');

        if(fontSize){
            all[i].style.fontSize=(parseFloat(fontSize)*factor)+"px";
        }
        if(all[i].nodeName === "IMG"){
            var width=style.getPropertyValue('width');
            var height=style.getPropertyValue('height');
            all[i].style.height = (parseFloat(height)*factor)+"px";
            all[i].style.width = (parseFloat(width)*factor)+"px";
        }
    }
</script>

as the the accepted answer mentioned, you can enlarge the fontSize css attribute of the element in DOM one by one, the following code for your reference.

 <script>
    var factor = 1.2;
    var all = document.getElementsByTagName("*");
    for (var i=0, max=all.length; i < max; i++) {
        var style = window.getComputedStyle(all[i]);
        var fontSize = style.getPropertyValue('font-size');

        if(fontSize){
            all[i].style.fontSize=(parseFloat(fontSize)*factor)+"px";
        }
        if(all[i].nodeName === "IMG"){
            var width=style.getPropertyValue('width');
            var height=style.getPropertyValue('height');
            all[i].style.height = (parseFloat(height)*factor)+"px";
            all[i].style.width = (parseFloat(width)*factor)+"px";
        }
    }
</script>
不顾 2024-08-01 05:16:52

最简单的解决方案

要获得窗口缩放(不是CSS缩放),有一些方法,但最简单的方法如下:

(function() {
    window.addEventListener('resize', evt => {
        let zoom = (window.outerWidth / window.innerWidth).toFixed(2)
        console.log('zoom: ', zoom, '%')
    })
})();

另一种方法

另一种方法是窗口.devicePixelRatio,但它可能会显示不正确的值,具体取决于屏幕分辨率(特别是多个屏幕)。

Easiest Solution

To get window zoom (not CSS zoom), there are some ways, but the easiest of them is as follows:

(function() {
    window.addEventListener('resize', evt => {
        let zoom = (window.outerWidth / window.innerWidth).toFixed(2)
        console.log('zoom: ', zoom, '%')
    })
})();

Another Way

An alternative way is window.devicePixelRatio, but it may display incorrect value, depending on screen resolution (specially with multiple screens).

梦里兽 2024-08-01 05:16:52

browser.tabs.setZoom() 应该处理这种情况。

let zooming = browser.tabs.setZoom(
  tabId,           // optional integer
  zoomFactor       // number
)

请参阅 MDN 文档:https:// /developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/setZoom

browser.tabs.setZoom() should handle this case.

let zooming = browser.tabs.setZoom(
  tabId,           // optional integer
  zoomFactor       // number
)

See the MDN Docs: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/setZoom

当梦初醒 2024-08-01 05:16:52
<html>
  <head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script>
        var currFFZoom = 1;
        var currIEZoom = 100;

        function plus(){
            //alert('sad');
                var step = 0.02;
                currFFZoom += step;
                $('body').css('MozTransform','scale(' + currFFZoom + ')');
                var stepie = 2;
                currIEZoom += stepie;
                $('body').css('zoom', ' ' + currIEZoom + '%');

        };
        function minus(){
            //alert('sad');
                var step = 0.02;
                currFFZoom -= step;
                $('body').css('MozTransform','scale(' + currFFZoom + ')');
                var stepie = 2;
                currIEZoom -= stepie;
                $('body').css('zoom', ' ' + currIEZoom + '%');
        };
    </script>
    </head>
<body>
<!--zoom controls-->
                        <a id="minusBtn" onclick="minus()">------</a>
                        <a id="plusBtn" onclick="plus()">++++++</a>
  </body>
</html>

在 Firefox 中不会改变缩放,只会改变比例!

<html>
  <head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script>
        var currFFZoom = 1;
        var currIEZoom = 100;

        function plus(){
            //alert('sad');
                var step = 0.02;
                currFFZoom += step;
                $('body').css('MozTransform','scale(' + currFFZoom + ')');
                var stepie = 2;
                currIEZoom += stepie;
                $('body').css('zoom', ' ' + currIEZoom + '%');

        };
        function minus(){
            //alert('sad');
                var step = 0.02;
                currFFZoom -= step;
                $('body').css('MozTransform','scale(' + currFFZoom + ')');
                var stepie = 2;
                currIEZoom -= stepie;
                $('body').css('zoom', ' ' + currIEZoom + '%');
        };
    </script>
    </head>
<body>
<!--zoom controls-->
                        <a id="minusBtn" onclick="minus()">------</a>
                        <a id="plusBtn" onclick="plus()">++++++</a>
  </body>
</html>

in Firefox will not change the zoom only change scale!!!

宛菡 2024-08-01 05:16:52

您可以使用 Window.devicePixelRatio 和 < a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia" rel="nofollow noreferrer">Window.matchMedia()

const onChange = e => {
  const pr = window.devicePixelRatio;
  const media = `(resolution: ${pr}dppx)`;
  const mql = matchMedia(media);

  const prString = (pr * 100).toFixed(0);
  const textContent = `${prString}% (${pr.toFixed(2)})`;

  console.log(textContent);
  document.getElementById('out').append(
    Object.assign(document.createElement('li'), {textContent})
  )

  mql.addEventListener('change', onChange, {once: true});
};

document.getElementById('checkZoom').addEventListener('click', e => onChange());

onChange();
<button id="checkZoom">get Zoom</button>
<ul id="out"></ul>

You can use Window.devicePixelRatio and Window.matchMedia()

const onChange = e => {
  const pr = window.devicePixelRatio;
  const media = `(resolution: ${pr}dppx)`;
  const mql = matchMedia(media);

  const prString = (pr * 100).toFixed(0);
  const textContent = `${prString}% (${pr.toFixed(2)})`;

  console.log(textContent);
  document.getElementById('out').append(
    Object.assign(document.createElement('li'), {textContent})
  )

  mql.addEventListener('change', onChange, {once: true});
};

document.getElementById('checkZoom').addEventListener('click', e => onChange());

onChange();
<button id="checkZoom">get Zoom</button>
<ul id="out"></ul>

烟织青萝梦 2024-08-01 05:16:52

您可以定位 CSS 的哪一部分缩小和缩小,或者整个 document.body.style.zoom

您可以设置最大和最小缩放级别。 这意味着,多次点击按钮 (+) 或 (-) 将不会放大或缩小。

var zoomingTarget = document.querySelector('.zooming-target')
var zoomInTool = document.getElementById('zoom-in');
var zoomOutTool = document.getElementById('zoom-out');

let zoomIndex = 0;

function zooming () {
    if (zoomIndex > 2) {
        zoomIndex = 2
    } else if (zoomIndex < -2) {
        zoomIndex = -2
    }
    zoomingTarget.style.zoom = "calc(100% + " + zoomIndex*10 + "%)";
}

现在使按钮 (+) 和 (-) 起作用。

zoomInTool.addEventListener('click', () => {
    zoomIndex++;
    if(zoomIndex == 0) {
        console.log('zoom level is 100%')
    }
    zooming();
})

zoomOutTool.addEventListener('click', () => {
    zoomIndex--
    if(zoomIndex == 0) {
        console.log('zoom level is 100%')
    }
    zooming();
})

由于 style.zoom 不适用于 Firefox,请考虑使用 style.transform = scale(x,y)。

You can target which part of CSS zooming out and in, or the entire document.body.style.zoom

You can set the maximum and minimum zoom levels. Meaning, more clicks on the button (+) or (-) will not zoom in more or zoom out more.

var zoomingTarget = document.querySelector('.zooming-target')
var zoomInTool = document.getElementById('zoom-in');
var zoomOutTool = document.getElementById('zoom-out');

let zoomIndex = 0;

function zooming () {
    if (zoomIndex > 2) {
        zoomIndex = 2
    } else if (zoomIndex < -2) {
        zoomIndex = -2
    }
    zoomingTarget.style.zoom = "calc(100% + " + zoomIndex*10 + "%)";
}

Now make the buttons (+) and (-) work.

zoomInTool.addEventListener('click', () => {
    zoomIndex++;
    if(zoomIndex == 0) {
        console.log('zoom level is 100%')
    }
    zooming();
})

zoomOutTool.addEventListener('click', () => {
    zoomIndex--
    if(zoomIndex == 0) {
        console.log('zoom level is 100%')
    }
    zooming();
})

Since style.zoom doesn't work on Firefox, consider using style.transform = scale(x,y).

暗喜 2024-08-01 05:16:52

我通过下面的代码修复了。

HTML:

<div class="mt-5"
        [ngStyle]="getStyles()">

TS:

getStyles() {
        const screenWidth = screen.width;
        const windowWidth = window.innerWidth;
        if (windowWidth != screenWidth) {
            const percentDifference = Math.ceil((screenWidth / windowWidth) * 100);
            if (percentDifference > 100) {
                this.bannerBackgroundImageSize = '20%, 74%';
            } else if (percentDifference === 100) {
                this.bannerBackgroundImageSize = '20%, 72%';
            } else if (percentDifference >= 90 && percentDifference <= 99) {
                this.bannerBackgroundImageSize = '25%, 70%';
            } else if (percentDifference >= 80 && percentDifference <= 89) {
                this.bannerBackgroundImageSize = '28%, 68%';
            } else if (percentDifference >= 75 && percentDifference <= 79) {
                this.bannerBackgroundImageSize = '29%, 67%';
            } else if (percentDifference >= 67 && percentDifference <= 74) {
                this.bannerBackgroundImageSize = '30%, 65%';
            } else if (percentDifference >= 50 && percentDifference <= 66) {
                this.bannerBackgroundImageSize = '30%, 61%';
            } else if (percentDifference < 50) {
                this.bannerBackgroundImageSize = '30%, 58%';
            }
        } else {
            this.bannerBackgroundImageSize = '20%, 72%';
        }
        const myStyles = {
            'background-size': this.bannerBackgroundImageSize,
        };
        return myStyles;
    }

我希望这适用于所有缩放级别,并且可以考虑使用所有样式。

有用的链接:

https://css-tricks.com/ can-javascript-detect-the-browsers-zoom-level/

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Backgrounds_and_Borders/Resizing_background_images

I fixed by the below code.

HTML:

<div class="mt-5"
        [ngStyle]="getStyles()">

TS:

getStyles() {
        const screenWidth = screen.width;
        const windowWidth = window.innerWidth;
        if (windowWidth != screenWidth) {
            const percentDifference = Math.ceil((screenWidth / windowWidth) * 100);
            if (percentDifference > 100) {
                this.bannerBackgroundImageSize = '20%, 74%';
            } else if (percentDifference === 100) {
                this.bannerBackgroundImageSize = '20%, 72%';
            } else if (percentDifference >= 90 && percentDifference <= 99) {
                this.bannerBackgroundImageSize = '25%, 70%';
            } else if (percentDifference >= 80 && percentDifference <= 89) {
                this.bannerBackgroundImageSize = '28%, 68%';
            } else if (percentDifference >= 75 && percentDifference <= 79) {
                this.bannerBackgroundImageSize = '29%, 67%';
            } else if (percentDifference >= 67 && percentDifference <= 74) {
                this.bannerBackgroundImageSize = '30%, 65%';
            } else if (percentDifference >= 50 && percentDifference <= 66) {
                this.bannerBackgroundImageSize = '30%, 61%';
            } else if (percentDifference < 50) {
                this.bannerBackgroundImageSize = '30%, 58%';
            }
        } else {
            this.bannerBackgroundImageSize = '20%, 72%';
        }
        const myStyles = {
            'background-size': this.bannerBackgroundImageSize,
        };
        return myStyles;
    }

I Hope this will work with all zoom levels and it can be considered with all styles.

Useful links:

https://css-tricks.com/can-javascript-detect-the-browsers-zoom-level/

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Backgrounds_and_Borders/Resizing_background_images

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文