所以我有一个 <img onload="resizeImage()" src="movie.gif">
在我的网站上,我只想在它完全加载后显示它。 gif 是通过 php 从我的 sql 数据库加载的,因此 img src 因页面而异。我也有调整大小以使图像全尺寸
<script type="text/javascript">
function resizeImage()
{
var window_height = document.body.clientHeight
var window_width = document.body.clientWidth
var image_width = document.images[0].width
var image_height = document.images[0].height
var height_ratio = image_height / window_height
var width_ratio = image_width / window_width
if (height_ratio > width_ratio)
{
document.images[0].style.width = "auto"
document.images[0].style.height = "100%"
}
else
{
document.images[0].style.width = "100%"
document.images[0].style.height = "auto"
}
}
</script>
是否可以将 gif 放在一个 div 中并执行此操作
#div {
display:none;
{
然后在加载图像后将 div 更改为此
#div {
display:block;
{
最佳答案
您可以使用此 HTML:
<img src="movie.gif" onload="displayImage(this)" style="display:none;">
使用这个 javascript:
function displayImage(obj) {
obj.style.display = "block";
}
在 HTML 中没有事件处理程序的另一种方法是动态创建对象,并且只在加载后将其插入页面,如下所示:
var img = new Image();
img.onload = function() {
document.body.appendChild(this);
};
img.src = "movie.gif";
或者,您也可以动态创建它,立即将其插入到 DOM 中,但仅在加载后才使其可见:
var img = new Image();
img.style.display = "none";
img.onload = function() {
this.style.display = "block";
};
img.src = "movie.gif";
document.body.appendChild(img);
好的,现在您已经展示了您的实际代码和 HTML,下面是一个考虑到附加信息并使用您现有代码的答案:
让你的 HTML 成为这样:
<img onload="resizeImage(this)" src="movie.gif" style="display:none;">
将您的代码更改为:
<script type="text/javascript">
function resizeImage(obj)
{
var window_height = document.body.clientHeight;
var window_width = document.body.clientWidth;
var image_width = obj.width;
var image_height = obj.height;
var height_ratio = image_height / window_height;
var width_ratio = image_width / window_width;
if (height_ratio > width_ratio)
{
obj.style.width = "auto";
obj.style.height = "100%";
}
else
{
obj.style.width = "100%";
obj.style.height = "auto";
}
obj.style.display = "block";
}
</script>
关于javascript - 加载后显示 gif,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12021926/