五星好評--cookie儲存上一次點選的資料

是火鍋吖發表於2020-11-01

思路
1.在哪裡儲存資料到cookie中
2.如何處理cookie資料
3.cookie資料回顯

import Component from "./Component.js";
export default class Star extends Component {
    static STAR_NUM = 5;
    label = "";
    starCon;
    face;
    score;
    pos = -1;
    starArr = [];
    static StarScoreList = {};
    constructor(_label) {
        super();
        this.label = _label;
        Object.assign(this.elem.style, {
            width: "auto",
            float: "left",
            height: "16px",
            paddingBottom: "10px",
            marginRight: "20px",
            paddingTop: "16px"
        })
        Star.StarScoreList[_label] = 0;
        this.createLabel(_label);
        this.createStar();
        this.createScore();
        //初始化顯示
        this.useCookie();
    }
	
	//使用cookie資料來回顯頁面資料
	//1.判斷初始值,如果不存在cookie資料時,則不使用cookie
	//2.當cookie有資料時,用cookie資料回顯
    useCookie() {
        var obj = this.getCookie();
        if (obj[this.label + "_score"] !== 0 && !isNaN(obj[this.label + "_score"])) {
            this.changeStar(Number(obj[this.label + "_score"]) - 1);
            this.changeScore(obj[this.label + "_score"]);
            //記錄點選的位置,防止頁面重新整理
            this.pos = Number(obj[this.label + "_score"]) - 1;
        }
    }

    createLabel(_label) {
        let labels = document.createElement("span");
        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, {
                width: "16px",
                height: "16px",
                float: "left",
                backgroundImage: "url(./img/commstar.png)",
            })
            this.starArr.push(star);
            this.starCon.appendChild(star);
        }
        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");
        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);
    }
    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,"\u5b8b\u4f53",sans-serif',
        });

        this.score.textContent = "0分";
        this.elem.appendChild(this.score);
    }

    mouseHandler(e) {
        switch (e.type) {
            case "click":
            case "mouseover":
                let index = this.starArr.indexOf(e.target);
                if (index < 0) return;
                if (e.type === "click") {
                    this.pos = index;
                    this.dispatch();
                    //記錄點選時資料,儲存在cookie中,以this.label + "_score=" + this.score.textContent形式儲存
                    document.cookie = this.label + "_score=" + this.score.textContent;
                }
                else {
                    this.changeScore(index + 1);
                    this.changeFace(index);
                }
                this.changeStar(index);
                break;
            case "mouseleave":
                this.changeStar(this.pos);
                this.changeScore(this.pos + 1);
                this.changeFace(-1);
                break;
        }
    }

    changeStar(n) {
        for (var i = 0; i < this.starArr.length; i++) {
            if (i <= n || i <= this.pos) {
                this.starArr[i].style.backgroundPositionY = "-16px";
            } else {
                this.starArr[i].style.backgroundPositionY = "0px";
            }
        }
    }
    changeScore(n) {
        this.score.textContent = n + "分";
        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
        }
        var index = Star.STAR_NUM - n - 1
        this.face.style.display = "block";
        this.face.style.backgroundPositionX = -index * 20 + "px";
        this.face.style.left = this.starArr[n].offsetLeft + "px";
    }
    dispatch() {
        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);

    }

    /**
     * 將點選時儲存的cookie取出, 返回物件列表
     */
    getCookie() {
        if (document.cookie.length == 0) return {};
        return document.cookie.split(";").reduce((value, item) => {
            var arr = item.split("=");
            value[arr[0].trim()] = arr[1].split("分")[0].trim();
            return value;
        }, {})
    }
}


相關文章