JS实现五星好评案例

本文实例为大家分享了JS实现五星好评案例的具体代码,供大家参考,具体内容如下
业务逻辑是我需要先创建出所有我需要用到的标签和样式再写出我们星星对应的行为,分数对应行为,笑脸对应行为,点击对应行为,抽象化出来,方便维护。并且在点击后我们抛出事件,记录下对应的name,分数等信息,保存在cookie中。
【JS实现五星好评案例】在编写过程中,一个是位置问题,很容易出现在没有创建就进行appendChild,第二个就是在添加行为时如何调整星星,笑脸的位置。

Document - 锐客网

export default class Component{//创建warp和 appendTo方法elem; constructor(){this.elem=this.createElem(); }createElem(){if(this.elem) return this.elem; let div=document.createElement("div"); return div; }appendTo(parent){if(typeof parent==="string")parent=document.querySelector(parent); parent.appendChild(this.elem); }}

import Component from "./Component.js"; export default class Star extends Component{label=""; score; face; starCon; static STAR_NUM=5; starArr=[]; static StarScoreList=[]; pos=-1; constructor(_label){super(); this.label=_label; Object.assign(this.elem.style,{width:"auto",height:"16px",float:"left",paddingBottom:"10px",marginRight:"20px",paddingTop:"16px",})Star.StarScoreList[_label]=0; this.createLable(_label); this.createStar(); this.createScore(); }createLable(_label){let labels=document.createElement("div"); labels.textContent=_label; Object.assign(labels.style,{float:"left",height: "16px",lineHeight: "16px",marginRight: "10px",overflow: "hidden",whiteSpace: "nowrap",textOverflow: "ellipsis",font: '12px/150% tahoma,arial,Microsoft YaHei,Hiragino Sans GB,"\u5b8b\u4f53",sans-serif',color: "#666"}); this.elem.appendChild(labels); }createStar(){this.starCon=document.createElement("div"); Object.assign(this.starCon.style,{float:"left",height:"16px",position:"relative",marginTop:"1px"})for(let i=0; ithis.mouseHandler(e))this.starCon.addEventListener("click",e=>this.mouseHandler(e))this.starCon.addEventListener("mouseleave",e=>this.mouseHandler(e))this.face=document.createElement("div"); }createScore(){this.score=document.createElement("span"); Object.assign(this.score.style,{position:"relative",width:"30px",height:"16px",top:"-2px",marginLeft:"10px",lineHeight:"16px",textAlign:"right",color:"#999",font:"12px/150% tahoma,arial,Microsoft YaHei,Hiragino Sans GB,sans-serif",}); this.score.textContent="0分"; this.starCon.appendChild(this.score); }mouseHandler(e){//鼠标行为let index=this.starArr.indexOf(e.target); switch(e.type){case "mouseover":if(index<0) return; this.changeFace(index); this.changeScore(index+1); this.changeStar(index+1); break; case "click":this.pos=index; this.dispatch(); break; case "mouseleave":this.changeStar(this.pos+1); this.changeFace(this.pos); this.changeScore(this.pos+1); break; default:return; }}changeStar(n){for(let i=0; i
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    推荐阅读