jquery - 脚本更改 div 大小,忽略 css

标签 jquery html css

几天前,同一个社区帮助我制作了一个脚本,用于将数组中的随机图像显示为 4 个 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;
}

这是布局应该如何的演示: http://codepen.io/anon/pen/ZWYywx

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> 的顶部、边距和填充设置为零,但它似乎没有用。有谁知道是什么原因造成的或如何预防?

最佳答案

尝试将 display: flex; 添加到您的 .box 类中。 Flexbox是解决所有 css 位置问题的绝佳解决方案 :)

关于jquery - 脚本更改 div 大小,忽略 css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35713852/

相关文章:

javascript - jQuery 加载多个 ul 列表的前 3 个元素

悬停功能的jQuery背景

html - 悬停属性不适用于一个元素但适用于另一个元素

html - 如何模仿html选择框

jquery - 将默认页面样式应用于从 ajax 调用返回的 html

css - 背景渐变问题

jquery - 如何创建一个返回另一个对象的 jQuery 函数?

javascript - jquery addClass() 在removeClass() 之后不起作用

jquery - 滑出导航 : Z-Index Issue

html - 在 coffeescript 中通过 ID 获取元素