jQuery 在 HTML 中将图像重新调整为原始大小的 50%

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11117602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:13:31  来源:igfitidea点击:

Image re-size to 50% of original size in HTML

jqueryhtmlimage

提问by Sam

I'm trying to re-size a image in HTML, it's got width 314px and height 212px. I want to re-size it to 50%...

我正在尝试在 HTML 中重新调整图像的大小,它的宽度为 314 像素,高度为 212 像素。我想将其大小重新调整为 50%...

but using this I still get a bigger image instead of a half-size image.

但是使用这个我仍然得到一个更大的图像而不是一个半尺寸的图像。

<img src="image.jpg" width="50%" height="50%" />

What did I do wrong? Thanks

我做错了什么?谢谢

<html>
    <head>
    <title></title>
    </head>    
    <body>
        <div>
        <img src="image4.png" width="50%" height="50%"/>
        </div>
    </body>
</html>

I resolved the above problem using jquery below:

我使用下面的 jquery 解决了上述问题:

$(document).ready(function(e) {
        var imgs = document.getElementsByTagName('img');
        var imgLength = imgs.length;

        for(var i=0; i<= imgLength-1;i++){

            var imgWidth = imgs[i].clientWidth;
            var imgHeight = imgs[i].clientHeight;

            $('img').eq(i).attr({width:imgWidth/2, height: imgHeight/2});

            console.log(imgWidth);
        }

        console.log(imgLength); 

    });

回答by Asif

You did not do anything wrong here, it will any other thing that is overriding the image size.

您在这里没有做错任何事情,它会覆盖图像大小的任何其他事情。

You can check this working fiddle.

你可以检查这个工作小提琴

And in this fiddleI have alter the image size using %, and it is working.

这个小提琴中,我使用 改变了图像大小%,并且它正在工作。

Also try using this code:

也尝试使用此代码:

<img src="image.jpg" style="width: 50%; height: 50%"/>?

Here isthe example fiddle.

这是示例小提琴。

回答by Skippy le Grand Gourou

The percentage setting does not take into account the original image size. From w3schools?:

百分比设置不考虑原始图像大小。来自w3schools?:

In HTML 4.01, the width could be defined in pixels or in % of the containing element. In HTML5, the value must be in pixels.

在 HTML 4.01 中,宽度可以以像素或包含元素的百分比来定义。在 HTML5 中,该值必须以像素为单位。

Also, good practice advice from the same source?:

此外,来自同一来源的良好实践建议?:

Tip: Downsizing a large image with the height and width attributes forces a user to download the large image (even if it looks small on the page). To avoid this, rescale the image with a program before using it on a page.

提示:使用 height 和 width 属性缩小大图像会强制用户下载大图像(即使它在页面上看起来很小)。为避免这种情况,请在页面上使用图像之前使用程序重新缩放图像。

回答by Nalan Madheswaran

We can do this by css3 too. Try this:

我们也可以通过 css3 来做到这一点。尝试这个:

.halfsize {
    -moz-transform:scale(0.5);
    -webkit-transform:scale(0.5);
    transform:scale(0.5);
}

<img class="halfsize" src="image4.jpg">
  • subjected to browser compatibility
  • 受浏览器兼容性影响