【问题标题】:I want to randomly place an image in boundaries of parent div我想将图像随机放置在父 div 的边界中
【发布时间】:2018-09-02 20:05:07
【问题描述】:

我有一些代码显示一个或两个随机图像形成一个列表并将其放置在 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>

【问题讨论】:

  • 请添加生成的 html 而不是 php,以便更好地说明正在发生的事情

标签: javascript php html image position


【解决方案1】:

在js中获取每张图片的宽高... 获取父级的宽度和高度.. 将图像随机放置在 0,0 到 (parent_width-img_width+1),(parent_height-img_height+1) 之间

注意:js 新手,所以确切的代码可能略有不同,但一般概念是准确的

在数学函数中替换它

var tLeft = Math.floor(Math.random() * ($(el).parent().width()-$(el).clientwidth+1)) + 'px',
    tTop  = Math.floor(Math.random() * ($(el).parent().height()-$(el).clientheight+1)) + 'px';

如果尺寸是自动的,它可能会弄乱值

编辑 1:代码中的错误

【讨论】:

  • 图片大小不同,高度设置为自动。我似乎无法运行此代码。我想我明白了,但为什么我们要添加宽度和高度?我们不应该减去它们吗?
【解决方案2】:

因为 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';

【讨论】:

猜你喜欢
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-06
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多