lynxerzhang / JSSkills

MIT License
0 stars 0 forks source link

使用js设置渐变色遇到的问题 #18

Open lynxerzhang opened 5 years ago

lynxerzhang commented 5 years ago

利用css的backgroundImage属性可以设置渐变色,但是利用js来动态设置时,设置颜色值的时候有个地方需要注意,不然可能造成显示问题(比如css属性添加不上)。

这个需要注意的就是颜色值本身。

问题重现:

//我需要把这个数组中的每一个项,变成字符串,比如第一项0xff2a46,经过转换就是#ff2a46,

var d = [0xff2a46,0xff7522,0xd8c206,0x09d49d,0x3c78ff,0x991aff];

//利用toString方法,可以很容易做到。
//下面这个数组就是转换过的。

var e = ["#ff2a46", "#ff7522“, "#d8c206", "#9d49d", "#3c78ff", "#991aff"];

但是很快发现,无法添加渐变色,查了好久发现0x09d49d变成了"#9d49d", 这个本身没有问题,但是就是因为少了个0,就不显示渐变色了, 所以,做了个判断,24位颜色值的16进制值字符串因为长度最长就是6,所以可以判断下,如果长度不满6,字符串前面就填充0。 那“#9d49d”就变成了“#09d49d”,修改后发现显示正常

//gradientBackgroundColorList传进来的是一个颜色值数组,比如[0xFF0000, 0xFFFF00, 0xFF00FF]
Object.defineProperty(CoreComment.prototype, "gradientBackgroundColorList", {
        get: function () {
            return this._gradientBackgroundColorList;
        },
        set: function (c) {
            this._gradientBackgroundColorList = c;
            if(this._gradientBackgroundColorList){
                var list = this._gradientBackgroundColorList;
                var g_css = ["left"];
                for(var i = 0; i < list.length; i ++){
                    g_css.push("#" + list[i].toString(16)); //这个版本粗看没有什么问题
                }
                this.dom.style.backgroundImage = "-webkit-linear-gradient(" + g_css.join(",") + ")";
            }
            else{
                this.dom.style.backgroundImage = "none";
            }
        },
        enumerable: true,
        configurable: true
});
//修正版本
Object.defineProperty(CoreComment.prototype, "gradientBackgroundColorList", {
        get: function () {
            return this._gradientBackgroundColorList;
        },
        set: function (c) {
            this._gradientBackgroundColorList = c;
            if(this._gradientBackgroundColorList){
                var list = this._gradientBackgroundColorList;
                var g_css = ["left"];
                var c = "";
                for(var i = 0; i < list.length; i ++){
                    c = list[i].toString(16);
                    if(c.length < 6){
                        c = (new Array((6 - c.length) + 1).join("0")) + c; //关键在于这个判断,如果字符长度不满6,就需要用0来填充
                    }
                    g_css.push("#" + c);
                }
                this.dom.style.backgroundImage = "-webkit-linear-gradient(" + g_css.join(",") + ")";
            }
            else{
                this.dom.style.backgroundImage = "none";
            }
        },
        enumerable: true,
        configurable: true
});