星级评分(全星)
想法是,一张empty.png(空心的星),一张full.png(实心的星),然后mouse事件切换
html
<div id="content"></div> <!--星是动态插入的-->
css
#content{
width: 500px;
height: 200px;
border: 1px solid grey;
margin: 0 auto;
display: flex;
justify-content: center;
align-items: center;
}
.star{
width: 50px;
height: 50px;
margin: 5px;
background: url(empty.png) no-repeat;
}
js
- 想试着用面对对象思想去写
//动态添加星
var addStar = function(num){
for(let i = 0; i < num; i++){
let div = document.createElement('div')
div.className = 'star'
document.getElementById("content").appendChild(div)
}
}
var Star = function(num){
//以一个类封装所有的属性和方法
var o = {}
starList = document.getElementsByClassName('star')
flag = true
//清除实心
clearStar = function(){
for(let i = 0; i < num; i++){
starList[i].style.backgroundImage = "url('empty.png')"
}
console.log('ok');
}
//鼠标移动到星上 & flag == tre
onMouse = function(i){
if(flag){
for(let j = 0; j <= i; j++){
starList[j].style.backgroundImage = "url('full.png')"
}
}
}
//鼠标移出星 & flag == true
offMouse = function(i){
if(flag){
for(let j = 0; j <= i; j++){
starList[j].style.backgroundImage = "url('empty.png')"
}
}
}
//点击星(将flag设为false就不会触发onmouseout事件
onClick = function(i){
flag = false
clearStar()
for(let j = 0; j <= i; j++){
starList[j].style.backgroundImage = "url('full.png')"
}
}
o.do = function(){
for(let i = 0; i < num; i++){
starList[i].onmouseover = function(){
onMouse(i)
}
starList[i].onmouseout = function(){
offMouse(i)
}
starList[i].onclick = function(){
onClick(i)
}
}
}
return o //返回这个类
}
//主函数 do thing
var main = function(){
addStar(5)
var star = Star(5)
star.do()
}
main()