Javascript object starting with random position

2019-08-07 12:41发布

问题:

I have 3 logo image (#logo, #logo2, #logo3) that move randomly around the page with my javascript:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2    /jquery.min.js"></script>
<script type="text/javascript">
    function moveDiv() {
    var $span = $("#logo");

    $span.fadeOut(500, function() {
      var maxLeft = $(window).width() - $span.width();
      var maxTop = $(window).height() - $span.height();
      var leftPos = Math.floor(Math.random() * (maxLeft + 10))
      var topPos = Math.floor(Math.random() * (maxTop + 10))

      $span.css({ left: leftPos, top: topPos }).fadeIn(2500); 

    });
  };

  moveDiv();
  setInterval(moveDiv, 2500);
</script>

My problem is that all of them start at the same position in the page (on top left corner) overlapping by themselves, only for the duration of the first fadeout. How can I let them start in a random position around the page since the first click on my webpage?

Thanks,

Michele

回答1:

Give them all the same class e.g logo and select them using this class :

var $spans = $(".logo");

Or use start with ^ selector :

var $spans = $("[id^='logo']");

And use each() to move them all, and you should set the position to absolute so the left/top rules can take effect :

div{
    position: absolute;
}

Hope this helps.

function moveDiv() {
  var $spans = $(".logo");

  $spans.each(function(){
    var _this = $(this);

    _this.fadeOut(500, function() {
      var maxLeft = $(window).width() - _this.width();
      var maxTop = $(window).height() - _this.height();
      var leftPos = Math.floor(Math.random() * (maxLeft + 10))
      var topPos = Math.floor(Math.random() * (maxTop + 10))

      _this.css({ left: leftPos, top: topPos }).fadeIn(100); 
      console.log(leftPos,topPos);
    });
  });
};

moveDiv();
setInterval(moveDiv, 1000);
div{
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="logo" id="logo" > LOGO</div>
<div class="logo" id="logo1" > LOGO 1</div>
<div class="logo" id="logo2" > LOGO 2</div>
<div class="logo" id="logo3" > LOGO 3</div>



回答2:

Set your logos' positions on some random values in theonload event, for example:

$(window).load(function() {
    // your init function with random values
});


回答3:

There are few moments that are important here:

  1. If you don't add images dynamically they should have different top and left coordinates initially so they don't flash from the same position.
  2. You need to get image loaded or assigned width/height-attribute before getting its proper dimensions. You can preload them by assigning src attribute directly on the DOM object.
  3. You need to specify style for the images to be positioned properly. I suggest position: fixed; as it positions relative to the viewport and don't move elements as page is scrolled.
  4. There is no need for additional setIntervalcall because fadeIn/fadeOut already have timers inside.

Here is the demo:

function moveDiv() {
  var span = $("#container"),
    images = [
      'https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png?v=c78bd457575a',
      'http://cdn.sstatic.net/Sites/stackexchange/img/apple-touch-icon.png',
      'http://cdn.sstatic.net/Sites/music/img/apple-touch-icon.png'
    ],
    src,
    wind = $(window),
    left = function(width) {
      return Math.floor(Math.random() * (wind.width() - width + 10));
    },
    top = function(height) {
      return Math.floor(Math.random() * (wind.height() - height + 10));
    },
    updateCSS = function(img) {
      var _this = img || this;
      _this.css({
        left: left(_this.width()),
        top: top(_this.height())
      });
    },
    cycle = function(img) {
      var _this = img || this;
      _this.fadeOut(2500, updateCSS.bind(_this)).fadeIn(500, cycle.bind(_this));
    };

  while (src = images.shift()) {
    var img = $('<img />');
    img[0].src = src; // preload image to get proper dimensions

    updateCSS(img);
    span.append(img);
    cycle(img);
  }
};

$(moveDiv);
#container img {
  position: fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<span id="container"></span>