源码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<meta name="Generator" content="Sublime Text3">
<meta name="Author" content="深山一枯柴">
<meta name="website" content="http://www.lihui-v.top">
<meta name="Description" content="马不停蹄的🐌!">
<style type="text/css">
* {
padding: 0;
margin: 0;
}
ul {
list-style: none;
font-size: 30px;
color: gold;
}
li {
float: left;
}
</style>
</head>
<body>
<ul>
<li>☆</li>
<li>☆</li>
<li>☆</li>
<li>☆</li>
<li>☆</li>
</ul>
<script type="text/javascript">
// 获取所有的li
var lis = document.getElementsByTagName('li');
// 获取父元素ul
var ul_box = document.getElementsByTagName('ul')[0];
// 给父元素添加onmouseover事件
ul_box.onmouseover= function (evt){
var event = evt || window.event;
// 利用事件委托确定点击的是那个li
if (event.target.nodeName.toLowerCase()=="li") {
// 根据li的位置推断当前点击的是那个li,num是几就是那个li
var num = parseInt(event.target.offsetLeft/30);
// 将类数组转换成数组
var newArry = Array.from(ul_box.children);
// 获取点击的这个li之前的所有li变成实心
var subArry = newArry.splice(0,num+1);
for (var i = 0; i < subArry.length; i++) {
subArry[i].innerHTML = "★";
}
// 剩余的都是空心
for (var i = 0; i < newArry.length; i++) {
newArry[i].innerHTML = "☆";
}
}
}
ul_box.onclick= function (evt){
var event = evt || window.event;
// 只给点击的这一个li添加id
for (var i = 0; i < this.children.length; i++) {
this.children[i].id = "";
}
if (event.target.nodeName.toLowerCase()=="li") {
event.target.id = "clicked"
}
}
ul_box.onmouseout= function (evt){
var event = evt || window.event;
for (var i = 0; i < this.children.length; i++) {
this.children[i].innerHTML = "☆";
}
// 获取点击的这个li
if (event.target.nodeName.toLowerCase()=="li") {
var select = document.getElementById('clicked');
// 将点击的这个li之前的li都设置实心
if (select) {
var num = parseInt(select.offsetLeft/30);
var newArry = Array.from(ul_box.children);
var subArry = newArry.splice(0,num+1);
for (var i = 0; i < subArry.length; i++) {
subArry[i].innerHTML = "★";
}
}
}
}
</script>
</body>
</html>
网友评论