jQuery attr无法正常工作

new*_*bie 2 jquery attributes

我在容器中有图像,我在CSS中为此图像设置了宽度和高度属性.但我需要添加加载图像,它比将在容器中显示的实际图片小,所以我需要在加载时更改图像的大小.但是当我设置宽度和高度属性时,图像显示在CSS中设置的大小.

$(img).attr("src", "loading.gif");
$(img).show();
$(img).attr("width", "100px");
$(img).attr("height", "100px");
Run Code Online (Sandbox Code Playgroud)

Sam*_*son 5

您将属性与CSS混淆:

$(img)
  .attr("src", "loading.gif")
  .css({width:100,height:100})
  .show();
Run Code Online (Sandbox Code Playgroud)

当然这假设img实际上代表了一个图像:

var img = $("img.myImage");
Run Code Online (Sandbox Code Playgroud)

如果您没有图像,则需要创建一个图像,然后将其附加到DOM:

$("<img>")
  .attr("src", "loading.gif")
  .css({width:100,height:100})
  .appendTo("body");
Run Code Online (Sandbox Code Playgroud)