九宫格随机位置的照片墙
1、需要用一个数组来记录九宫格的位置
2、需要一个数组,用来记录一下随机出现li的下标
3、写一个随机函数。
首先css代码,布局一个九宫格
body,
div,
h2,
ul,
li {
margin: 0;
padding: 0;
}
.box {
width: 644px;
margin: 0 auto;
background: #eee;
border: 1px solid #b8b8b8;
overflow: hidden;
}
.title a {
float: right;
color: black;
outline: none;
}
.title a:hover {
color: red;
}
#box {
position: relative;
}
.box li {
float: left;
width: 200px;
height: 200px;
padding: 6px;
background: #fff;
border: 1px solid #c3c3c3;
display: inline;
list-style: none;
transition: 1s all;
}
.box li img {
width: 100%;
height: 100%;
}
a {
position: absolute;
left: 30px;
top: 30px;
}
html的布局,









随机
js代码
window.onload = function () {
var oBox = document.getElementById('box');
var oCBox = document.getElementsByClassName('box')[0];
var oHeight = oCBox.offsetHeight;
oCBox.style.height = oHeight + 'px'
var oChild = oBox.children;
// li的 left top 的位置的值存进数组
var arr = [];
// 随机下标数组
var oRan = []
// 点击事件的开关,防止点击两次位置错乱
var flog = true;
// init 初始化一下 改为用定位
// 先获取一下每个li位置(left,top)存到arr数组里面
init();
// 循环每个给每个li 添加上定位,位置
for (let o = 0; o < arr.length; o++) {
oChild[o].style.position = 'absolute';
oChild[o].style.left = arr[o].l + 'px';
oChild[o].style.top = arr[o].t + 'px';
}
// 点击事件
var oA = document.getElementsByTagName('a')[0];
oA.onclick = function () {
// 开关为false的直接停止
if (!flog) return;
flog = false;
// 添加oRan 数组下标的随机数;(要随机li下标随机数)
for (var j = 0; j < arr.length; j++) {
let num = ran(0, arr.length);
// 去重一下 不能有一样的下标
if (oRan.indexOf(num) === -1) {
oRan.push(num);
} else {
j--;
}
}
// 开始以oRan数组随机下标 来循环li的下标 把每个li添加位置 添加随机位置
for (let n = 0; n < oRan.length; n++) {
let m = oRan[n]
oChild[m].style.left = arr[n].l + 'px';
oChild[m].style.top = arr[n].t + 'px';
}
// 添加之后为空
oRan = [];
setTimeout(() => {
//1 秒之后吧开关改为true;
flog = true;
}, 1000)
}
// 随机函数
function ran(m, n) {
return parseInt(Math.random() * (m - n) + n);
}
function init(){
arr = [];
for (let i = 0; i < oChild.length; i++) {
arr.push({
l: oChild[i].offsetLeft,
t: oChild[i].offsetTop
})
}
}
}
最后全部代码
照片墙一多实例演示









随机
本文章为个人写,并非转载!!!!!!
欢迎评论!!!