简体   繁体   English

Gif图片仅在完全加载后才调整大小

[英]Gif image only resizes after fully loaded

Gif will only resize after the gif is fully loaded. 只有在gif完全加载后,gif才会调整大小。 How do I make the gif resized whilst even loading? 加载时如何调整gif大小?

I use multiple gifs so they come in different sizes so I can not just do the usual 100% height and width, I want to keep the aspects correct. 我使用了多个gif,因此它们的大小不同,因此我不能只执行通常的100%的高度和宽度,而是要保持各个方面正确。

The script I use to resize the gif 我用来调整gif大小的脚本

<script>
function resizeToMax(id){
    myImage = new Image() 
    var img = document.getElementById(id);
    myImage.src = img.src; 
    if(myImage.width / document.body.clientWidth > myImage.height / document.body.clientHeight){
        img.style.width = "100%";
    } else {
        img.style.height = "100%";
    }
}
</script>

The php to display the image php显示图片

<?php 
echo '<img id="image" onload="resizeToMax(this.id)" src="gifs/' . $myTokens[1] . '/' . $myTokens[2] . '.gif">';
?>   

Use window.onload event to make sure your resizing will be effective at beginning of window loading. 使用window.onload事件来确保您的大小调整将在窗口加载开始时生效。

<script>
window.onload = function() {
    resizeToMax("image");
};

function resizeToMax(id){
    myImage = new Image() 
    var img = document.getElementById(id);
    myImage.src = img.src; 
    if(myImage.width / document.body.clientWidth > myImage.height / document.body.clientHeight){
        img.style.width = "100%";
    } else {
        img.style.height = "100%";
    }
    document.getElementById(id).style.display = "block";
}
</script>

<?php 
echo '<img id="image" style="display:none;" src="gifs/' . $myTokens[1] . '/' . $myTokens[2] . '.gif">';
?> 

Or hide your image in css and show it in your function after your resizing. 或在调整大小后将图像隐藏在CSS中并在函数中显示。

您可能能够做的一件事是隐藏图像,直到图像被加载(例如,添加CSS类),然后在resizeToMax函数中,删除隐藏图像的CSS类。

The onload events fire only when image has finished loading. 仅当图像加载完成时才会触发onload事件。 In the meanwhile, you could play with the css width and / or height properties, or even max-width and max-height. 同时,您可以使用CSS的width和/或height属性,甚至可以使用max-width和max-height。

The risk is that you don't know the image proportions yet, so the image may looks distorted ehile loading. 风险是您尚不知道图像比例,因此图像看起来在半透明加载时会变形。

IMHO the best solution is to replace the image with a placeholder, load the image without displaying it (eg. outside of the screen window), then resizing and displaying it in the correct position removing the placeholder. 恕我直言,最好的解决方案是用占位符替换图像,在不显示图像的情况下加载图像(例如,在屏幕窗口之外),然后调整大小并将其显示在正确的位置,以除去占位符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM