【问题标题】:Placeholder image the size of the image area?占位符图像图像区域的大小?
【发布时间】:2014-03-13 04:40:45
【问题描述】:

在加载时创建加载图像以代替 .gif 的最佳方法是什么?我想要一个大约 325x325(gif 大小)的占位符图像来保存内容。

我没有成功尝试过 background: url() 并且没有研究过 JS/jQuery,因为我不是很精通。

提前感谢您的帮助。

【问题讨论】:

  • 到目前为止你能发布你的代码吗?
  • 当你说 background:url() 不起作用时,它做了什么?您是否将背景的容器元素设置为 display:block (或类似的)并在其上设置宽度和高度?它可能正在工作,但为 0px x 0px
  • 相关代码不多。这是一张以页面为中心、id 为“eye”的单张图片。当我使用相同大小的图像设置 background:url() 时,当链接不可用时,图像就会消失。

标签: javascript jquery image background placeholder


【解决方案1】:

如果您可以或想要使用 jQuery,您可以使用 onLoad 函数来加载图像并在加载后执行一些操作(例如将加载的 gif 替换为图像)。

结帐this JSFiddle。它使您可以显示立即加载的图像,以及需要 1000 毫秒才能加载的图像。

这是怎么做到的?看看这段代码:

var url="http://i.imgur.com/QoRjjFu.jpg", //the URL of the image to load
    image=$("#some-image"),               //get the image element           
    newImage = new Image();               //create a new image 

//this is called after the image loads
newImage.onload = function(){
    image.attr('src', url).show();  //swap out the loading gif
};

//this triggers loading the image, which will trigger onload above when done
newImage.src = url;

现在,如果图像加载速度很快,您不希望快速闪烁加载 gif,然后切换新图像(因为它会导致闪烁效果)。您想一起跳过加载 gif,只显示图像。您可以通过使用超时来做到这一点,并且仅在新图像尚未加载时才显示加载 gif,例如 200 毫秒:

var url="http://i.imgur.com/QoRjjFu.jpg",
    image=$("#some-image"),
    newImage = new Image();

newImage.onload = function(){
    clearTimeout(loadingGif); //clear the loading gif timeout
    image.attr('src', url).show();
};

//if the image hasn't loaded after 200ms, show the loading gif
var loadingGif = setTimeout(function(){
   image.show();
}, 200);

newImage.src = url;

我希望这会有所帮助!

【讨论】:

  • 我没有理由相信这不起作用,但我似乎无法切换图像,尽管准确复制了脚本并将 id 更改为 some-image。知道是什么原因造成的吗?
  • 您尝试过 JSFiddle 吗?您需要将其附加到事件中,即使该事件只是页面的 onload 事件。
  • 我该怎么做呢?提前致谢
  • 把它包裹在$(function{ ... });里面
猜你喜欢
  • 2015-11-17
  • 1970-01-01
  • 2014-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-26
  • 2019-04-23
  • 1970-01-01
相关资源
最近更新 更多