前端入坑纪 36
如题,继续上回效果 -> 《简单的星星评价》效果 的 升级版!
当然拉,其实星星图片也就加了一张半星而已。
OK,first things first!项目链接
滑动出半星HTML 结构
<div class="mWrp">
<p>您的评价:</p>
<p id="starWrp">
<a href="javascript:;"></a>
<a href="javascript:;"></a>
<a href="javascript:;"></a>
<a href="javascript:;"></a>
<a href="javascript:;"></a>
</p>
</div>
结构和上回的一样,简洁有效!
CSS 结构
body {
padding: 0;
margin: 0;
background-color: #F4F4F4;
}
p {
padding: 0;
margin: 0;
}
ul,
li {
padding: 0;
margin: 0;
list-style: none;
}
a {
text-decoration: none;
color: #525252;
}
img {
vertical-align: middle;
}
.fl {
float: left;
}
.fr {
float: right;
}
.clear::after {
display: block;
content: "";
clear: both;
}
.mWrp {
width: 100%;
margin: 0 auto;
max-width: 640px;
}
.mWrp p {
margin: 6px 0;
padding: 8px;
}
#starWrp {
display: inline-block;
}
#starWrp a {
display: inline-block;
height: 30px;
width: 30px;
background-image: url(star00.png);
background-size: 100% auto;
background-position: center center;
margin: 0 3px;
}
#starWrp a.on {
background-image: url(star10.png);
}
#starWrp a.onaf {
background-image: url(star05.png);
}
添加半颗星星的背景
JS 结构
var stars = document.getElementById("starWrp");
var als = stars.getElementsByTagName('a');
var startX = endX = counter = 0;
stars.addEventListener("touchstart", function(evt) {
startX = evt.targetTouches[0].clientX;// 获取触摸起始点的clientX值
});
stars.addEventListener("touchmove", function(evt) {
endX = evt.targetTouches[0].clientX;// 获取滑动时变化的clientX值
var cNum = Number(endX - startX);// 数字化clientX的差值
var bNum = cNum / 30 <= 5 ? cNum / 30 : 5;// 这里其实就是if else的简化。如果 cNum / 30 小于等于5,则取改值,否则取5
// 先重置所有星星为空
for (var j = 0; j < als.length; j++) {
als[j].className = "";
}
// 将到bNum为止的星星点亮
for (var m = 0; m < bNum; m++) {
als[m].className = "on";
}
// 判断bNum是否在半颗的区间,如果是,点亮半个星星效果
for (var n = 0; n < als.length; n++) {
if (bNum > n && bNum < n + 0.5) {
als[n].className = "onaf";
}
}
// 将bNum赋给全局变量counter
counter = bNum;
});
// 用counter判断星级数,并控制台打印
stars.addEventListener("touchend", function(evt) {
switch (true) {
case counter == 0:
console.log("零星")
break;
case counter > 0 && counter < 0.5:
console.log("半星")
break;
case counter > 0.5 && counter < 1:
console.log("一星")
break;
case counter > 1 && counter < 1.5:
console.log("一颗半星")
break;
case counter > 1.5 && counter < 2:
console.log("两星")
break;
case counter > 2 && counter < 2.5:
console.log("两颗半星")
break;
case counter > 2.5 && counter < 3:
console.log("三星")
break;
case counter > 3 && counter < 3.5:
console.log("三颗半星")
break;
case counter > 3.5 && counter < 4:
console.log("四星")
break;
case counter > 4 && counter < 4.5:
console.log("四颗半星")
break;
case counter > 4.5:
console.log("五星")
break;
}
});
依言更新了昨天承诺的效果,不过,总感觉最后的switch 函数有点傻!。那么有兴趣的同学,可以好好研究一翻,期待你我共同进步!!!
好了,到此,本文告一段落!感谢您的阅读!祝你身体健康,阖家幸福!
网友评论