0

If I have the following:

<img src="filler.jpg" class="imgClass" delays="otherImage.jpg" delayw="400" delayw="600" delayt="Loaded">
<img src="filler.jpg" class="imgClass" delays="otherImage2.jpg" delayw="450" delayw="600" delayt="Loaded 2">

$(document).ready(function() {
    $(".imgClass").each(function(){
        $(this).attr("src", $(this).attr("delays"));
        $(this).attr("width", $(this).attr("delayw"));
        $(this).attr("height", $(this).attr("delayh"));
        $(this).attr("title", $(this).attr("delayt"));
     });
})

Is there a way I can have the width, height and title attributes only change after the src attribute has finished changing? With the above code they seem to all change at the same time. In a perfect world I'd like them to happen one at a time. At a minimum I'd like the src to change then the other three to change right after that since the src changes takes a slight bit of time.

4

3 回答 3

2

您可以使用.onload回调。这是一个没有 jQuery 的版本:

var img = document.getElementsByClassName('imgClass');
for (var i = 0, n = img.length; i < n; ++i) {
     var el = img[i];
     el.onload = function() {
         this.width = this.getAttribute('delayw');
         this.height = this.getAttribute('delayh');
         this.title = this.getAttribute('delayt');
     };
     el.src = this.getAttribute('delays');
});

注意:为了获得更好的 HTML5 兼容性,请使用data-foo属性而不是自己编写。

于 2013-06-09T21:21:10.193 回答
1

load检索图像后触发事件:

$(".imgClass").each(function(){
    this.src = $(this).attr("delays"));
}).one('load', function() {  // `.one` executes the event handler only once
    var $this = $(this);
    $this.attr({
        width: $this.attr('delayw'),
        height: $this.attr('delayh'),
        title: $this.attr('delayt')
    });
});

将值分配给 DOM 属性通常比分配给 HTML 属性更可取,因此您可能需要考虑使用.prop而不是.attr.

于 2013-06-09T21:21:08.027 回答
0

你可以这样做 -

$(".imgClass").each(function(){
        $(this).attr("src", $(this).attr("delays"));
        $(this).on('load',function(){
          $(this).attr("width", $(this).attr("delayw"));
          $(this).attr("height", $(this).attr("delayh"));
          $(this).attr("title", $(this).attr("delayt"));
        })
})

;

于 2013-06-09T21:21:40.463 回答