随机排列
css
* {
margin: 0;
padding: 0;
}
ul {
width: 810px;
margin: 0 auto;
position: absolute;
}
input {
margin-top: 30px;
width: 100px;
height: 30px;
line-height: 30px;
border: 1px solid #ccc;
background: #009999;
color: #fff;
}
li {
margin-top: 50px;
list-style: none;
width: 200px;
height: 300px;
text-align: center;
float: left;
}
img {
width: 200px;
height: 280px;
}
.clearFix::before .clearFix::after {
content: '';
clear: both;
display: block;
line-height: 0;
}
html
<input type="button" value="从大到小" />
<input type="button" id="btn" value="随机排序" />
<ul>
<li>
<img src="./img/1.jpg" alt="">
<p>图片1</p>
</li>
<li>
<img src="./img/2.jpg" alt="">
<p>图片2</p>
</li>
<li>
<img src="./img/3.jpg" alt="">
<p> 图片3</p>
</li>
<li>
<img src="./img/4.jpg" alt="">
<p>图片4</p>
</li>
<li>
<img src="./img/5.jpg" alt="">
<p> 图片5</p>
</li>
<li>
<img src="./img/6.jpg" alt="">
<p> 图片6</p>
</li>
<li>
<img src="./img/7.jpg" alt="">
<p>图片7</p>
</li>
<li>
<img src="./img/8.jpg" alt="">
<p>图片8</p>
</li>
</ul>
js
var btn = document.getElementById('btn');
var aLi = document.getElementsByTagName('li');
var Inp = document.getElementsByTagName('input');
var Img = document.getElementsByTagName('img');
var oP = document.getElementsByTagName('p');
var url = ['./img/1.jpg', './img/2.jpg', './img/3.jpg', './img/4.jpg', './img/5.jpg', './img/6.jpg', './img/7.jpg', './img/8.jpg'];
var tit = ['图片01', '图片02', '图片03', '图片04', '图片05', '图片06', '图片07', '图片08'];
var num = [0, 1, 2, 3, 4, 5, 6, 7];
Inp[0].off = true
// 从大到小
Inp[0].onclick = function () {
if (this.off) {
num.sort(function (a, b) { return b - a })
str();
Inp[0].off = false
} else {
// 从小到大
num.sort(function (a, b) { return a - b })
str();
Inp[0].off = true;
}
function str() {
for (var i = 0; i < aLi.length; i++) {
Img[i].src = url[num[i]]
oP[i].innerHTML = tit[num[i]]
}
}
}
// 随机顺序
btn.onclick = function () {
var no = [];
while (no.length < url.length) {
var ou = parseInt(Math.random() * url.length);
if (no.indexOf(ou) == -1) {
no.push(ou);
}
}
for (var i = 0; i < aLi.length; i++) {
Img[i].src = url[no[i]];
oP[i].innerHTML = tit[no[i]];
}
}
效果图