最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - random position of images - Stack Overflow

programmeradmin2浏览0评论

i found a script that would position divs / images randomly. However, it isn't pletely working the way i want/need it to.

The images are loaded each within a div (which isn't ideal i guess). I have around 30 images.

But they don't load nicely and var posy = (Math.random() * ($(document).height() - 0)).toFixed(); doesn't work nicely either. The images mostly load on top (i think that the images in the blog don't count so it gets the height without images?)

So what I want: Load the in more nicely Randomize them so they get to the bottom of the page, too

var circlePosition = document.getElementsByClassName('circle');
console.log(circlePosition);

function position() {
  for (var i = 0; i < circlePosition.length; i++ ) {
    //give circle a random position
    var posx = (Math.random() * ($(document).width() - 0)).toFixed();
    var posy = (Math.random() * ($(document).height() - 0)).toFixed();



    //apply position to circle
    $(circlePosition[i]).css({
      'position':'absolute',
      'left':posx+'px',
      'top':posy+'px',
    })
  } 
} //end function position

var circleTotal = circlePosition.length;

$('.circle').click(function() {
  $(this).fadeOut();
  circleTotal = circleTotal - 1;
  console.log(circleTotal);

  if(circleTotal == 0) {
    position()
    $('.circle').fadeIn();
  }

});

position();
<script src=".1.1/jquery.min.js"></script>
<img src="//placehold.it/1x5000"> <!-- Placeholder image to show issue -->
<div class="circle">
  <img src=".png">
</div>
<div class="circle">
  <img src=".png">
</div>

i found a script that would position divs / images randomly. However, it isn't pletely working the way i want/need it to.

The images are loaded each within a div (which isn't ideal i guess). I have around 30 images.

But they don't load nicely and var posy = (Math.random() * ($(document).height() - 0)).toFixed(); doesn't work nicely either. The images mostly load on top (i think that the images in the blog don't count so it gets the height without images?)

So what I want: Load the in more nicely Randomize them so they get to the bottom of the page, too

var circlePosition = document.getElementsByClassName('circle');
console.log(circlePosition);

function position() {
  for (var i = 0; i < circlePosition.length; i++ ) {
    //give circle a random position
    var posx = (Math.random() * ($(document).width() - 0)).toFixed();
    var posy = (Math.random() * ($(document).height() - 0)).toFixed();



    //apply position to circle
    $(circlePosition[i]).css({
      'position':'absolute',
      'left':posx+'px',
      'top':posy+'px',
    })
  } 
} //end function position

var circleTotal = circlePosition.length;

$('.circle').click(function() {
  $(this).fadeOut();
  circleTotal = circleTotal - 1;
  console.log(circleTotal);

  if(circleTotal == 0) {
    position()
    $('.circle').fadeIn();
  }

});

position();
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="//placehold.it/1x5000"> <!-- Placeholder image to show issue -->
<div class="circle">
  <img src="http://static.tumblr./tensqk8/k8anq0438/01.png">
</div>
<div class="circle">
  <img src="http://static.tumblr./tensqk8/k8anq0438/01.png">
</div>

Share Improve this question edited Aug 6, 2015 at 16:55 anka asked Aug 5, 2015 at 21:42 ankaanka 991 gold badge2 silver badges9 bronze badges 2
  • It actually worked OK for me: appeared to be fairly random and I didn't see images unevenly distributed near top of page. But I was going to post same ment as MCM: try $(window).load(position); because the load event fires after all images have loaded, and if images do not have height defined the doc height may change. You might be getting very fast response.. put a breakpoint in your current call to position(); and check the value of $(document).height(). Mine was about 15,000 px or so. Also: don't do random images. It is poor UX unless you add collision detection for your content. – nothingisnecessary Commented Aug 5, 2015 at 21:57
  • I've edited your snippet with a very tall image to show the issue. @MCM's answer is correct, it should be in an window.onload or $(window).load() event listener. Also, you should notice that this only happens the first time you load the page, after the images have loaded the result will be cached. – user4639281 Commented Aug 5, 2015 at 21:57
Add a ment  | 

2 Answers 2

Reset to default 1

A clean and readable and solution without a jQuery dependence might be something like this. It avoids unnecessarily wrapping your images in divs by positioning the images themselves. It includes a hidden element as a sort of "poor man's" shadow DOM.

http://jsfiddle/sean9999/yv9otwr7/9/

;(function(window,document,undefined){
    "use strict";
        var init = function(){    
            var canvas = document.querySelector('#x');
            var icon_template = document.querySelector('#template');
            var icon_width = 40;
            var icon_height = 30;
            var the_images = [
                'http://static.tumblr./tensqk8/k8anq0438/01.png',
                'http://static.tumblr./tensqk8/rYanq05el/04.png',
                'http://static.tumblr./tensqk8/SYknq05py/05.png',
                'http://static.tumblr./tensqk8/s7inq057d/03.png'
            ];
            var pickRandomImage = function(){
                var i = Math.floor( Math.random() * the_images.length );
                return the_images[i];
            };
            var total_number_of_images = 10;
            var max_height = canvas.offsetHeight - icon_height;
            var max_width = canvas.offsetWidth - icon_width;
            var randomCoordinate = function(){
                var r = [];
                var x = Math.floor( Math.random() * max_width );
                var y = Math.floor( Math.random() * max_height );
                r = [x,y];
                return r;
            };
            var createImage = function(){
                var node = icon_template.cloneNode(true);
                var xy = randomCoordinate();
                node.removeAttribute('id');
                node.removeAttribute('hidden');
                node.style.top = xy[1] + 'px';
                node.style.left = xy[0] + 'px';
                node.setAttribute('src',pickRandomImage());
                canvas.appendChild(node);
            };
            for (var i=0;i<total_number_of_images;i++){
                createImage();
            };
        };
       window.addEventListener('load',init);
})(window,document);
body {
    background-color: #fed;
}

#x {
    border: 3px solid gray;
    background-color: white;
    height: 400px;
    position: relative;
}

#x .icon {
    position: absolute;
    z-index: 2;
}
<h1>Randomly distributed images</h1>

<div id="x"></div>

<img src="#" class="icon" hidden="hidden" id="template" />

try moving your position(); call inside the $(window).load function.

I think maybe the images are being positioned before all the images have loaded, so the page is shorter then.

发布评论

评论列表(0)

  1. 暂无评论