JS achieves five-star praise case

JS achieves five-star praise case

This article shares the specific code of JS to achieve five-star praise for your reference. The specific content is as follows

The business logic is that I need to first create all the tags and styles I need to use, and then write the corresponding behaviors of our stars, scores, smiley faces, and clicks, abstract them for easy maintenance. And after clicking, we throw an event, record the corresponding name, score and other information, and save it in a cookie.

During the writing process, one is the position problem, which is easy to appear when appendChild is performed without creating it. The second is how to adjust the position of stars and smiley faces when adding behaviors.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script type="module">
        import Star from "./js/Star.js";
        let list=["Product Conformity","Shop Service Attitude","Express Delivery Speed","Courier Service","Express Packaging"]
        list.forEach(item => {
            let star = new Star(item);  
            star.appendTo("body");
            star.addEventListener("change",changeHandler);
        });

        function changeHandler(e){
            var date = new Date();
            date.setMonth(11);
            setCookie(e.scoreList,date);
            
            function setCookie(data,date){ //Store in cookie in JSON format var str=date===undefined ? "" : ";expires="+date.toUTCString();
                for(var prop in data){
                    var value=data[prop];
                    if(typeof value==="object" && value!==null) value=JSON.stringify(value);
                    document.cookie=prop+"="+value+str;
                }
            }
        }
    </script>
</body>
</html>
export default class Component{ //Create warp and appendTo methods 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;i<Star.STAR_NUM;i++){
            let star = document.createElement("div");
            Object.assign(star.style,{
                backgroundImage:"url(./img/commstar.png)",
                width:"16px",
                height:"16px",
                float:"left",
            })
            this.starArr.push(star);
            this.starCon.appendChild(star);
        }
        Object.assign(this.face.style,{
            width:"16px",
            height:"16px",
            backgroundImage:"url(./img/face-red.png)",
            position:"absolute",
            top:"-16px",
            display:"none"
        });
        this.starCon.appendChild(this.face);
        this.elem.appendChild(this.starCon);
        this.starCon.addEventListener("mouseover",e=>this.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 points";
        this.starCon.appendChild(this.score);
    }
    mouseHandler(e){ //Mouse behavior 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<this.starArr.length;i++){
            if(i<n){
                this.starArr[i].style.backgroundPositionY="-16px";
            }else{
                this.starArr[i].style.backgroundPositionY="0px";
            }
        }
    }
    changeScore(n){
        this.score.textContent=n+"points";
        if(n===0){
            this.score.style.color="#999";
            
        }else{
            this.score.style.color="#e4393c";
        }
    }
    changeFace(n){
        if(n<0){
            this.face.style.display="none";
            return;
        }
        let index=Star.STAR_NUM-n-1; //The smiley face here is reversed because of the picture this.face.style.display="block";
        this.face.style.backgroundPositionX=-index*20+"px";
        this.face.style.left=this.starArr[n].offsetLeft+"px";
    }
    changeScore(n){
        this.score.textContent=n+"points";
        if(n===0){
            this.score.style.color="#999";
        }else{
            this.score.style.color="#e4393c";
        }
    }
    dispatch(){
        // console.log("aaa")
        Star.StarScoreList[this.label]=this.pos+1;
        var evt = new Event("change");
        evt.score=this.pos+1;
        evt.label=this.label;
        evt.scoreList=Star.StarScoreList;
        this.dispatchEvent(evt);
    }
}

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • JS achieves five-star praise effect
  • JavaScript implements five-star product evaluation
  • Implement five-star reviews based on jQuery
  • Five-star review function implemented by jQuery [Case]
  • jQuery's method of imitating five-star rating function based on layers
  • js realizes the five-star evaluation function
  • JavaScript to achieve five-star rating function
  • JavaScript to implement five-star rating code (source code download)
  • JS and JQuery respectively realize Taobao five-star praise special effects

<<:  MySQL 8.0.21 installation and configuration method graphic tutorial

>>:  Tomcat9 download, installation and configuration + detailed tutorial on integrating into eclipse

Recommend

How to set a fixed IP address for a VMware virtual machine (graphic tutorial)

1. Select Edit → Virtual Network Editor in the me...

A few things you need to know about responsive layout

1. Introduction Responsive Web design allows a we...

【HTML element】How to embed images

The img element allows us to embed images in HTML...

Detailed explanation of the usage of the alias command under Linux

1. Use of alias The alias command is used to set ...

HTML tutorial, HTML default style

html , address , blockquote , body , dd , div , d...

Docker exec executes multiple commands

The docker exec command can execute commands in a...

Example analysis of the use of GROUP_CONCAT in MySQL

This article uses an example to describe how to u...

MySQL 8.0.15 download and installation detailed tutorial is a must for novices!

This article records the specific steps for downl...

Restart all stopped Docker containers with one command

Restart all stopped Docker containers with one co...

Detailed explanation of Linux file operation knowledge points

Related system calls for file operations create i...

A few front-end practice summaries of Alipay's new homepage

Of course, it also includes some personal experien...

HTML uses marquee to achieve text scrolling left and right

Copy code The code is as follows: <BODY> //...

React realizes secondary linkage effect (staircase effect)

This article shares the specific code of React to...

Vue uses three methods to refresh the page

When we are writing projects, we often encounter ...