javascript - 我想将图像随机放置在父 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>
解决方案
由于 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';
推荐阅读
- python - 在python中插入排序后的二进制搜索
- scala - 是否可以在扩展的 scala 类中扩展方法?
- javascript - 如何将图像 url 从 firebase 显示到 html 表中?
- sql - 使用上一行的值和下一行的值计算平均值
- android - 安卓服务是否会因为从不安全的网络从 Play 商店下载应用程序而被黑客入侵
- java - 在 Java 中锁定文件通道时出现 OverlappingFileLockException
- javascript - img.onload 在新的 Image() 声明后拒绝触发
- asp.net-core - 如何使用 Swashbuckle.AspNetCore v5.0.0-rc2 记录 API 密钥身份验证
- c++ - 将子变量传递给父构造函数
- apache-spark - 火花高阶函数变换输出结构