开发者

Generating random divs multiple times on load

开发者 https://www.devze.com 2023-03-16 19:37 出处:网络
let me just give a quick story. I have made a page. (VERY simple - two divs with a different background image, see here.)

let me just give a quick story. I have made a page. (VERY simple - two divs with a different background image, see here.)

Anyway, I need to make it so that when a new page loads, the two divs that I have load in a ran开发者_C百科dom order over and over, filling the entire screen content. So there's no pattern of the first div and then the second, it's just randomly generated. Sort of like a huge grid, with the two divs repeated with no pattern.

My question is...is that possible? I assume I'd need to know PHP, but I have no knowledge of it.

Thanks guys, I appreciate all help!


http://jsfiddle.net/uYPRq/

jquery

var div1 = '<div class="one">';
var div2 = '<div class="two">';

var len = 
    Math.floor(window.innerWidth/30)*Math.floor(window.innerHeight/30);

for (x = 0; x < len; x++) {   
    if ( Math.random() > 0.5 ) {
        $(div1).appendTo('body');
    }
    else {
        $(div2).appendTo('body');
    }
}

css

div.one, div.two {
    height:30px;
    width:30px;
    float:left;
}

div.one { background-color:#EBE1E4; }
div.two { background-color:#F0F5DF; }

edit: changed screen.availWidth to window.innerWidth


Something like so? Just loop through how ever many times you like and add elements in.

for (i = 0; i < 300; i++) {
    var type1 = document.createElement("div");
    var type2 = document.createElement("div");
    type1.innerHTML = "div1";
    type2.innerHTML = "div2";
    type1.setAttribute("class", "type1");
    type2.setAttribute("class", "type2");
    document.body.appendChild(type1);
    document.body.appendChild(type2);
}


No PHP needed. This can be done client-side using Javascript (Jquery might be easier).

0

精彩评论

暂无评论...
验证码 换一张
取 消