我想在父 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>

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

注意:js 的新功能,因此确切的代码可能略有不同,但一般的 cocept 是准确的

在数学函数中替换它

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:代码中的错误

由于 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';

最新更新