使用jQuery创建图像网格 [英] Creating a grid of images with jQuery

查看:65
本文介绍了使用jQuery创建图像网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Web编程和jQuery的新手.我想加载图像并将它们排列在网格中.但是,要加载的图像数量不是固定的.我有一个数组img_arr,每个图片的网址和ID.

I'm very new to web programming and jQuery. I want to load images and arrange them in a grid. However, the number of images to be loaded is not fixed. I have an array, img_arr, with the url and an id for each image.

加载和定位图像的代码如下:

The code that loads and positions images is like this:

var t = 0;
var l = 0;
for (i = 0; i < img_arr.length; i++) {
    var img = new Image();
    $(img)
        .attr('src', img_arr[i]['url'])
        .attr('id',  img_arr[i]['id'])
        .load(function(){
            $('#container').append( $(this) );
            // Your other custom code
            $(this).css( {
                "position": "absolute",
                     "top": t + 'px',
                    "left": l + 'px'
            });
        });
    l = l + 50;
    if (l > 300) {
        t = t + 50;
        l = 0;
    }
}

但是,图像在最终的偏移位置处彼此重叠.有人知道为什么会这样吗?

But, the images get placed on top of each other at the final offset location. Anyone know why this happens?

推荐答案

姆哈哈哈! [邪恶的笑声]

Mwahaha! [Evil laughter]

这里有一个错误,一个常见的,隐蔽的错误,与图像,CSS或jQuery无关.这是Javascript中的后期绑定错误.

There's an error here, a common, insidious error, one that has nothing to do with images, or CSS, or jQuery. It's the late-binding error in Javascript.

OP使用变量tl表示顶部"和左侧"(顺便说一句,OP,topleft作为变量名出了什么问题),并在循环中递增它们并在回调中调用它们.但是tl后期绑定.调用onload函数时,这些变量将设置为它们的 final 值,而不是它们在创建image标签时所具有的值.

The OP uses the variables t and l to mean "top" and "left" (incidentally, OP, what is wrong with top and left as variable names), incrementing them in a loop and invoking them at a callback. But t and l are late bound. When the onload functions are called, those variables are set to their final values, not the values they had when the image tag was created.

因此,图像在最终的偏移位置彼此重叠".

And so, "the images get placed on top of each other at the final offset location".

尝试一下:

var renderImage = function(imgdesc, t, l) {
   var img = new Image();
    $(img)
        .attr('src', imgdesc['url'])
        .attr('id',  imgdesc['id'])
        .load(function(){
            $('#container').append( $(this) );
            // Your other custom code
            $(this).css( {
                "position": "absolute",
                     "top": t + 'px',
                    "left": l + 'px'
            });
        });
};

var t = 0;
var l = 0;
for (i = 0; i < img_arr.length; i++) {
    renderImage(img_arr[i], t, l)
    l = l + 50;
    if (l > 300) {
        t = t + 50;
        l = 0;
    }
}

这篇关于使用jQuery创建图像网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆