简体   繁体   English

JS随机函数和砖石引起的问题

[英]JS Random function and masonry causing issues

I'm using this code below so randomly place images, within a container, from each other. 我在下面使用此代码,以便将图像彼此随机地放置在容器中。 The effect works well, however, for most of the time, the function fails to load and on visiting, and all the images display awkwardly over each other on the page. 该效果效果很好,但是,在大多数情况下,该功能无法加载和无法访问,并且所有图像在页面上彼此尴尬地显示。

$(document).ready(function(){
  $('.each-image').each(function() {
    $(this).css({ 
       'margin-top':  Math.floor((Math.random() * 300) +1) + 'px', 
       'margin-left': Math.floor(Math.random() * 400 + 0) + 'px' });
  });
});

I am also using masonry in combination with this to avoid an overlap. 我还结合使用砖石,以避免重叠。 The masonry is called first and organised the images, then the random function extends the distances between them all. 首先将砌体称为图像并组织图像,然后随机函数会扩展它们之间的距离。

Masonry code: 砌体代码:

$(document).ready(function(){
var $container = $('.content-side.individual-pages');

$container.imagesLoaded( function(){
    $container.masonry({
    itemSelector : '.each-image',
    columnWidth: 30,
    isAnimated: true
  });
});
});

Here's a link to the project: http://www.sarahstaton.com/exhibitions-installations/ and if you refresh , you'll see sometimes it works, and sometimes it doesn't. 这里是该项目的链接: http : //www.sarahstaton.com/exhibitions-installations/如果您刷新,您会看到有时它起作用,有时却不起作用。

My question, really, is if I should be using anything else, or what could I do to tighten up the random function. 我的问题确实是,我是否应该使用其他任何东西,或者该怎么做才能加强随机函数。

Thanks, R 谢谢,R

There is nothing in the code that guarantee that the images are not overlaping each other what I can see. 代码中没有任何东西可以保证图像不会彼此重叠,我所看到的。

Remove the Masonry code and just irritate thru the collection of "each-image" and guarantee you are using a unique margin-top on each of the images/or how do you want. 取出砌体代码,只是激怒通“每个图像”的收集,保证您使用的每个图像的一个独特的margin-top /或你想要怎么做。

$(document).ready(function(){
  var i = 0;
  $('.each-image').each(function() {
    i++;
    $(this).css({ 
       'margin-top':  (Math.floor((Math.random() * 300) +1) * (i*400)) + 'px', // Or change the facator to the images size
       'margin-left': Math.floor(Math.random() * 400 + 0) + 'px' });
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM