如何为动态 img 元素添加尺寸

发布于 2024-08-30 03:59:10 字数 849 浏览 7 评论 0原文

我使用 Json 调用来获取图像地址列表,然后将它们单独添加到这样的 div 中。不幸的是,图像尺寸不是 Json 信息的一部分。

<div id="container">
   <img src="A.jpg" alt="" />
   <img src="B.jpg" alt="" />
   ...
</div>

你们中的任何 JQuery 天才是否知道可以完美地动态地将真实的 WidthHeight 添加到容器中的每个 img 元素的代码< strong>每个单独的渲染完成后?

我在想也许代码可以进行图像宽度检查 width > 0 来评估图像何时实际渲染,然后触发。但我不知道如何去做并使其稳定工作。解决这个问题的最佳方法是什么?

更新,正如答案所指出的,将宽度高度添加到 元素很常规。这 这里的问题实际上是写一个 知道何时做什么的代码 那。并评估该条件 每张图片而不是整个页面。

更新2
我找到了一个非常好的工作答案 这里

I use a Json call to get a list of image addresses, then I add them individually to a div like this. Unfortunately the image dimension is not part of the Json information.

<div id="container">
   <img src="A.jpg" alt="" />
   <img src="B.jpg" alt="" />
   ...
</div>

Do any of you JQuery geniuses know of a code that would flawlessly and dynamically add the true Width and Height to each img element in the container as soon as each individual one is rendered?

I was thinking maybe the code could do a image width check width > 0 to evaluate when the image has actually been rendered, then fire. But I wouldn't know how to go about that and make it work stably. How is the best way of going about this?

Update, As the answers point out, adding Width or Height to the
elements is pretty routine. The
problem here is actually writing a
code that would know when to do
that. And evaluate that condition for
each image not the page as a whole.

Update 2
I found a very nice working answer here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

只为守护你 2024-09-06 03:59:10

试试这个:

$('#container img').css('height', function(index, value){
    return $(this).height()+ 'px';
})
$('#container img').css('width', function(index, value){
    return $(this).width() + 'px';
})

编辑

好的,我已经尝试过类似的方法,当我使用 firebug 检查元素时,高度和宽度属性是否具有正确的值......

$(document).ready(function(){

  $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",
        function(data){
          $.each(data.items, function(i,item){
            $("<img/>").attr("src", item.media.m).appendTo("body");
            if ( i == 999 ) return false;
          });
          $('img').css('height', function(index, value){
              return $(this).height()+ 'px';
          });
          $('img').css('width', function(index, value){
              return $(this).width()+ 'px';
          });
  });
})

演示

try this:

$('#container img').css('height', function(index, value){
    return $(this).height()+ 'px';
})
$('#container img').css('width', function(index, value){
    return $(this).width() + 'px';
})

EDITED

ok, I have tried something like this and when I inspect the elements using firebug, height and width attribute is there withe right values....

$(document).ready(function(){

  $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",
        function(data){
          $.each(data.items, function(i,item){
            $("<img/>").attr("src", item.media.m).appendTo("body");
            if ( i == 999 ) return false;
          });
          $('img').css('height', function(index, value){
              return $(this).height()+ 'px';
          });
          $('img').css('width', function(index, value){
              return $(this).width()+ 'px';
          });
  });
})

demo

夜清冷一曲。 2024-09-06 03:59:10

是的,可以,您可以使用 width()height() jQuery 方法来获取图像的尺寸。

更多信息:

根据评论更新:

负载 甚至在所有图像和外部资源与 DOM 一起加载到页面中时触发,因此您可以使用它并使用 width()height()获取图像尺寸的方法。例子:

$(window).load(function(){
  // your code to get dimensions, manipulate images, etc
})

Yes, you can, you can use the width() and height() jQuery methods to get the dimensions of the images.

More info:

Update based on comment:

The load even is fired when all images and external resources have loaded into the page along with the DOM, so you can use that and use the width() and height() methods to get the dimensions of the images. Example:

$(window).load(function(){
  // your code to get dimensions, manipulate images, etc
})
顾挽 2024-09-06 03:59:10

使用 $(document).ready() 等待图像完全加载。

准备好(处理程序)

handler - DOM 准备好后执行的函数。

虽然 JavaScript 提供了在页面渲染时执行代码的 load 事件,但只有在完全接收到所有资源(例如图像)后,才会触发该事件。

Reigel 的解决方案,现在使用 $(document).ready():

$(document).ready(function() {
    $('#container img').css('height', function(index, value){
        return $(this).height()+ 'px';
    });
    $('#container img').css('width', function(index, value){
        return $(this).width() + 'px';
    });
});

[编辑]: 刚刚意识到,当您在页面加载后插入图像时,这可能不起作用,但我想值得一试:

$('#mydiv').html('<img .../><script language="javascript" type="text/javascript">$(document).ready(...)</script>');

Use $(document).ready() to wait for the images to be completely loaded.

ready (handler)

handler - A function to execute after the DOM is ready.

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received.

Reigel's solution, now with the use of $(document).ready():

$(document).ready(function() {
    $('#container img').css('height', function(index, value){
        return $(this).height()+ 'px';
    });
    $('#container img').css('width', function(index, value){
        return $(this).width() + 'px';
    });
});

[EDIT]: Just realized that this may not work when you insert the images after the page has loaded but I guess it's worth a try:

$('#mydiv').html('<img .../><script language="javascript" type="text/javascript">$(document).ready(...)</script>');
神也荒唐 2024-09-06 03:59:10
$('#container img').each(function(){
var pic_real_width;
var pic_real_height;

$(img).load(function() {
    // Remove attributes in case img-element has set width and height
    $(this).removeAttr("width")
           .removeAttr("height")
           .css({ width: "", height: "" }); // Remove css dimensions as well

    pic_real_width = this.width;
    pic_real_height = this.height;
});

var src = img.src;
img.src = "";
img.src = src; // Triggers onload if image is cached
});

功劳归于 Xavi

$('#container img').each(function(){
var pic_real_width;
var pic_real_height;

$(img).load(function() {
    // Remove attributes in case img-element has set width and height
    $(this).removeAttr("width")
           .removeAttr("height")
           .css({ width: "", height: "" }); // Remove css dimensions as well

    pic_real_width = this.width;
    pic_real_height = this.height;
});

var src = img.src;
img.src = "";
img.src = src; // Triggers onload if image is cached
});

Credit goes to Xavi

倾`听者〃 2024-09-06 03:59:10

另一个建议:

通过 AJAX 在后台加载图像,并希望浏览器缓存它们,以便当您将元素添加到 div 时它们会立即出现(并且您可以立即检索 width() 和 height())。 ;)

如果您有权访问发送这些图像的网络服务器:请确保设置适当的缓存标头。

[编辑]:您也可以 放置图像数据,而不是依赖缓存,您刚刚通过 AJAX 直接将其加载到源代码中。不幸的是,这显然在 IE 中不起作用。

<img src="data:<mimetype>;base64,<data>" />

要对数据进行编码,请使用像这样的函数

Another suggestion:

Load the images via AJAX in the background and hope for the browser to cache them, so that they are instantly there when you add the elements to your div (and you can retrieve width() and height() immediately). ;)

If you have any access to the webserver which sends those images: Make sure you set the appropriate cache headers.

[EDIT]: Instead of relying on the cache you could also put the image data, which you just loaded via AJAX, directly into your source code. Unfortunately, this apparently doesn't work in IE.

<img src="data:<mimetype>;base64,<data>" />

To encode the data use a function like this one.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文