div内产生位置随机的图片

3 篇文章 0 订阅

本来想模拟一个扫雷的(只画样子,不实现功能),感觉太简单了。只要不停的向div内追加img标签就可以了。所以想弄麻烦点。

效果图:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<title></title>
		<meta charset="utf-8"/>
		<style type="text/css">
			*{margin:0;padding:0}
			#asj{
				width:550px;
				height:380px;
				margin:0 auto;
			}
			#content{
				width:550px;
				height:380px;
				border:1px solid red;
				position:fixed;
			}
		</style>
		<script src="./JS/jQuery-1.7.1.js" type="text/javascript"></script>
		<script type="text/javascript">
			$(function(){
				init();// 页面加载时开始在div上随机“画”图片
			});
			// 函数:初始化函数。
			function init(){
				// 页面图片的总数
				for(var i=1;i<=50;i++){
					// 通过getNum函数获取图片xy轴的坐标。
					var x=getNum(500),y=getNum(330);
					// 追加到div容器中。
					$("<img/>",{"id":"img"+i,"src":"black.gif"}).appendTo("#content").click(function(){
						alert("hello world");
					}).css({"top":y,"left":x,"position":"absolute"});
				}
			};
			// 函数:主动创建符合要求的整数,并返回。
			function getNum(limit){
				var num;
				while(true){
					num=Math.random()*1000;
					if(num<=limit&&num>0){
						break;
					}
				}
				return parseInt(num);
			};
		</script>
	</head>
	<body>
		<div id="asj">
			<div id="content">
				
			</div>
		</div>
	</body>
</html>


在网页设计中,如果需要创建div元素以随机大小和位置,并保证它们不会重叠,通常会通过JavaScript或CSS结合使用来实现。这是一个基本步骤: 1. **HTML结构**:首先,你需要一些基础的div容器元素,例如: ```html <div class="container"></div> ``` 2. **CSS样式**:设置一个包含所有div的基本样式,以及允许绝对定位的规则: ```css .container { position: relative; } .random-box { position: absolute; width: 0; height: 0; overflow: hidden; /* 隐藏溢出内容 */ } ``` 3. **JavaScript/jQuery**:动态生成并放置div,可以参考以下伪代码: ```javascript function createRandomBoxes(num) { for (let i = 0; i < num; i++) { const boxWidth = Math.floor(Math.random() * 200) + 50; // 随机宽度 const boxHeight = Math.floor(Math.random() * 200) + 50; // 随机高度 const left = Math.floor(Math.random() * window.innerWidth - boxWidth); // 随机左边界 const top = Math.floor(Math.random() * window.innerHeight - boxHeight); // 随机上边界 const newBox = document.createElement('div'); newBox.className = 'random-box'; newBox.style.width = `${boxWidth}px`; newBox.style.height = `${boxHeight}px`; newBox.style.left = `${left}px`; newBox.style.top = `${top}px`; container.appendChild(newBox); } } // 调用函数生成一定数量的div createRandomBoxes(10); ``` 4. **检查重叠**:为了防止重叠,你还可以添加一些碰撞检测算法,如`offsetTop`、`offsetLeft`属性来检查新元素是否与其他元素重叠。但这通常会在性能上造成负担,所以一般情况下,我们会尽量避免在生成时就考虑到这个问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值