我正在寻找一个类或可能的解决方案,以使用jQuery创建div或图片,并用较小的正方形填充它,如下所示:

jQuery能够做到这一点吗?

最佳答案

同样的例子:

var unitSize = 16; // width (and height) of one square
var unitsWide = 6; // number of squares along x-axis
var unitsTall = 6; // number of squares along y-axis
var drawing = $('<div class="drawing"></div>').css({
    overflow: 'hidden',
    border: '16px solid #000000',
    width: unitSize * unitsWide
});
for (var i = 0; i < unitsWide * unitsTall; i++) {
    var randomColor;
    randomColor = Math.random() * 0x1000000; // 0 < randomColor < 0x1000000
    randomColor = Math.floor(randomColor); // 0 < randomColor <= 0xFFFFFF
    randomColor = randomColor.toString(16); // hex representation randomColor
    randomColor = ("000000" + randomColor).slice(-6); // leading zeros added
    randomColor = "#" + randomColor; // # added
    $('<span class="square"></span>').css({
        display: 'block',
        float: 'left',
        width: unitSize,
        height: unitSize,
        'background-color': randomColor
    }).appendTo(drawing);
}
drawing.appendTo($("body"));

Demo here

10-05 21:46