首页 > 解决方案 > 我想将图像随机放置在父 div 的边界中

问题描述

我有一些代码显示一个或两个随机图像形成一个列表并将其放置在 div 中的随机位置。有时图像出现在 div 之外。如何包含仅显示在父 div 边界中的图像?

当前代码:

$('.draggable').each(function(i, el) {
  var tLeft = Math.floor(Math.random() * 99) + 1 + '%',
    tTop = Math.floor(Math.random() * 99) + 1 + '%';
  $(el).css({
    'left': tLeft,
    'top': tTop
  });
});
.draggable {
  position: absolute;
}

.top-images {
  position: relative;
  width: 700px;
  height: 80vh;
  margin: 0 auto;
}

.top-images img {
  width: 300px;
  height: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="top-images">
  <img class="draggable" src="http://serwer1858479.home.pl/autoinstalator/wordpress/wp-content/themes/cincio/img/main/main_page(9).jpg">
  <img class="draggable" src="http://serwer1858479.home.pl/autoinstalator/wordpress/wp-content/themes/cincio/img/main/main_page(3).jpg">
</div>

标签: javascriptphphtmlimageposition

解决方案


由于 300px(图像的宽度)是 700(图像出现的 div 的宽度)的 43%,因此您需要限制tleft为 57 (100-43)。但是tTop有点不同,因为您使用了像素。尝试这个 :

var maxTop = $('.top-images').first().height() - $(this).height(),
tLeft = Math.floor(Math.random() * 57) + 1 + '%',
tTop = Math.floor(Math.random() * maxTop) + 'px';

推荐阅读