Ajax瀑布流异步加载

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>瀑布流</title>
<script src="ajax.js"></script>
<style>
* {
margin: 0;
padding: 0;
}

body {
background: #f3f2f3;
}

#main {
border: 1px solid red;
width: 1225px;
margin: 0 auto;
}

.list {
width: 245px;
float: left;
}

.loadmore {
position: fixed;
width: 200px;
height: 30px;
left: 50%;
margin-left: -100px;
bottom: 10px;
}
</style>
</head>

<body>
<div id="main">
<div class="list a"></div>
<div class="list b"></div>
<div class="list c"></div>
<div class="list d"></div>
<div class="list e"></div>
</div>
<button id="cascadeBtn" class="loadmore">点击</button>
</body>
<script>
let list = Array.from(document.getElementsByClassName("list"))
window.onload = function () {
cascadeBtn.addEventListener("click", function () {
ajax({
url: "waterfall",
success: function (params) {
console.log(params);
params.forEach(img => {
let _img = document.createElement("img")
_img.src = img.src
_img.height=img.height
let minIndex = getShortIndex()
list[minIndex].appendChild(_img)
});
}
})
})
}
function getShortIndex() {
let minheight = getHeight(list[0])
let minIndex = 0
for (let i = 0; i < list.length; i++) {
let _height = getHeight(list[i])
if (_height < minheight) {
minheight = _height
minIndex = i
}
}
return minIndex
}
function getHeight(params) {
if (params.appendChild.length == 0) {
return 0
}
let sum = 0
for (let i = 0; i < params.children.length; i++) {
sum += Number(params.children[i].height)
}
return sum
}
 
//Ajax方法封装
function ajax(options) {
let defaults = {
type: "get"
}
Object.assign(defaults, options)
let xhr = null
if (window.VBArray) {
xhr = new ActiveXObject("Msxml2.XMLHTTP")
} else {
xhr = new XMLHttpRequest()
}
xhr.open(defaults.type, defaults.url)
xhr.onload = function () {
defaults.success ? defaults.success(JSON.parse(xhr.response)) : ""
}
if (defaults.type == "get") {
xhr.send()
}
if (defaults.type == "post") {
xhr.setRequestHeader("content-Type", "application/x-www-from-urlencoded")
xhr.send(defaults.data)
}
}
</script>

</html>

猜你喜欢

转载自www.cnblogs.com/sunyang-001/p/10828536.html