2016-03-01 87 views
4

几天前,我得到同一社区的帮助,制作脚本将数组中的随机图像显示为4个div。每个图像在更新和/或计时器时都会更改。
它工作得很好,直到我决定使用它关联到我一直在努力的CSS布局。脚本更改div大小,忽略css

HTML:

<section> 
    <div id="square_1" class='box'> 
    </div> 

    <div id="square_2" class='box'> 
    </div> 

    <div id="square_3" class='box'> 
    </div> 

    <div id="square_4" class='box'> 
    </div> 
</section> 

CSS:

body{ 
    width: 100%; 
    height: 100%; 
    background-color: #404040;  
} 
.box{ 
    position: relative; 
    width: 20%; /* desired width */ 
    background-color: #ffb3b3; 
    border: 10px solid #fff; 
} 
.box:before{ 
    content: ""; 
    display: block; 
    padding-top: 100%; /* initial ratio of 1:1*/ 
} 
.box img{ 
    width: 100%; 
} 
/* Positions */ 
#square_1{ 
    position: absolute; 
    margin-top: 2%; 
    margin-left: 42%; 
    z-index: 90; 
} 
#square_2{ 
    position: absolute; 
    margin-top: 22%; 
    margin-left: 2%; 
    z-index: 100; 
} 
#square_3{ 
    position: absolute; 
    margin-top: 48%; 
    margin-left: 27%; 
    z-index: 100; 
} 
#square_4{ 
    position: absolute; 
    margin-top: 34%; 
    margin-left: 73%; 
    z-index: 100; 
} 

这里的布局是如何应该是一个演示:

JQuery的

/* generate the array of images you want to choose from */ 
var srcarray = [ 
    "https://s-media-cache-ak0.pinimg.com/736x/7e/1d/4a/7e1d4a1566976f139a2ba58b108e2bce.jpg", 
    "http://rs832.pbsrc.com/albums/zz248/Paria53/Edited/Random.jpg~c200", 
    "http://images.freeimages.com/images/premium/large-thumbs/5187/51875120-random-numbers-forming-a-sphere.jpg", 
"http://www.islandstone.com/mediafiles/product_records/56_Random_lines_thumb.jpg" 
]; 

function randomizeImages() { 
    arr = []; 
    /* select unique images from the array and display them into relevant divs (any number divs allowed, should be less than available images)*/ 
    while(arr.length < $("section div").length){ 
    var randomnumber= srcarray[Math.floor(Math.random()*srcarray.length)]; 
    var found=false; 
    for(var i=0;i<arr.length;i++){ 
     if(arr[i]==randomnumber){found=true;break} 
    } 
    if(!found)arr[arr.length]=randomnumber; 
    $("section div:nth-child("+(i+1)+")").html('<img src="'+randomnumber+'">'); 
    }; 
} 

//randomize images when page is reloaded 
$(function() { 
randomizeImages(); 
}); 

//randomize images every 5 seconds (change interval as you wish) 
window.setInterval(function(){ 
    randomizeImages(); 
}, 5000); 

而这里发生了什么,当我将其与所述脚本相关联: http://codepen.io/anon/pen/RaNgvN

我也尝试了<img>顶部设置,保证金和填充为零,但它似乎没有工作。有没有人知道是什么原因导致它或如何防止它?

+0

http://codepen.io/anon/pen/PNwKPb – NiKoLaPrO

回答

3

尝试将display: flex;添加到您的.box类中。 Flexbox是一个很好的解决方案,您所有的CSS位置问题:)

+1

它的作品就像一个魅力!我真的必须记住下次flex! 谢谢! –

+0

请记住,在Internet Explorer中这不是很好的支持:http://caniuse.com/#feat=flexbox – KWeiss

+0

@KWeiss Internet Explorer用户习惯于看到一个混乱的,破碎的互联网 - 这是您付出的代价IE浏览器。你会避免建造一条全新的道路吗?因为有硬皮的旧车仍在开车? –