body部分
<div id="wrap">
<ul class="goods">
<!--外部获取数据,创建标签添加数据-->
</ul>
<ul class="btn">
<li>从高到低</li>
<li>从低到高</li>
<li>随机排序</li>
</ul>
</div>
样式部分
<style>
*{
margin: 0;
padding: 0;
font-family: "Microsoft Yahei";
list-style: none;
user-select: none; /*文本不能被选择 */
}
#wrap{
box-sizing: border-box;
width: 960px;
height: 630px;
padding: 40px 30px ;
border: 1px solid #aaa;
margin: 50px auto;
}
#wrap .goods{
overflow: hidden;
width: 100%;
}
#wrap .goods li{
position: relative;
box-sizing: border-box;
float: left;
width: 25%;
height: 240px;
padding: 10px 6px;
}
#wrap .goods li img{
display: block;
}
#wrap .goods li p.price{
position: absolute;
bottom: 10px;
right: 10px;
width: 50px;
height: 50px;
background-image: url(价格背景图片url);
color: #fff;
font-size: 14px;
line-height: 50px;
text-align: center;
font-style: oblique;
}
#wrap .goods li p.title{
font-size: 16px;
line-height: 30px;
}
#wrap .btn li{
float: right;
width: 90px;
height: 40px;
margin-top: 20px;
margin-right: 10px;
background-color: rgb(79, 189, 152);
line-height: 40px;
text-align: center;
font-size: 14px;
color: #fff;
cursor: pointer;
}
</style>
逻辑部分
<script>
(function(){
// 假装已获取到数据
let data = [
{
src : "商品图片Url",
price : 100,
title : ""
},
{
src : "",
price : 97,
title : ""
},
{
src : "",
price : 99.5,
title : ""
},
{
src : "",
price : 215,
title : ""
},
{
src : "",
price : 130,
title : ""
},
{
src : "",
price : 300,
title : ""
},
{
src : "",
price : 700,
title : ""
},
{
src : "",
price : 500,
title : ""
},
];
// 前端的数据处理
let oGoodsUl = document.querySelector("#wrap .goods"), oBtnLi = document.querySelectorAll("#wrap .btn li")
// 遍历data生成所需要的前端标签结构
init()
function init(){
let html = ""
data.forEach(item => {
html += `<li><img src="${item.src}" width="190" height="190">
<p class="price">¥<b>${item.price}</b></p>
<p class="title">${item.title}</p></li>`
})
oGoodsUl.innerHTML = html
}
// 封装添加点击事件
(function(){
let clickArr = [
(a,b) => b.price-a.price,
(a,b) => a.price-b.price,
(a,b) => Math.random()-0.5
]
oBtnLi.forEach((node,index) => {
// console.log(node); // 此处node指三个li
// console.log(index);
node.onclick = function(){
data.sort(clickArr[index])
init()
}
})
})()
// // 添加点击事件
// (function(){
// // 从高到低
// oBtnLi[0].onclick = function(){
// // 对data进行排序
// let sortway = (a,b) => b.price - a.price
// data.sort(sortway)
// // 写法二
// // data.sort((a,b) => b.price-a.price)
// init() // 重新渲染
// }
// // 从低到高
// oBtnLi[1].onclick = function(){
// // 对data进行排序
// let sortway = (a,b) => a.price - b.price
// data.sort(sortway)
// // 写法二
// // data.sort((a,b) => a.price-b.price)
// init() // 重新渲染
// }
// // 随机排序
// oBtnLi[2].onclick = function(){
// // 对data进行排序
// let sortway = Math.random()-0.5 // -0.5~0.5
// // 写法二
// // data.sort(()=>Math.random()-0.5)
// data.sort(sortway)
// init() // 重新渲染
// }
// })
})()
</script>