使用 jquery 设置背景渐变 - jshint 错误

Setting background gradient with jquery - jshint error

我正在尝试使用 jQuery 制作背景渐变动画,如下所示:

this.$next.css('line-indent', 0).animate({
    'line-indent': 100
}, {
    "duration": 750,
    "step": function(value) {
        $(this).css({
            "background": color,
            "background": "moz-radial-gradient (50% 50%, ellipse cover, transparent " + value + "%, " + color + " " + value + "%))",
            "background": "-webkit-radial-gradient(50% 50%, circle, transparent " + value + "%, " + color + " " + value + "%)",
            "background": "radial-gradient(circle at center, transparent " + value + "%, " + color + " " + value + "%)"
        })
    },
    "easing": 'easeInQuint',
    "complete": function() {
        $(this).css({
            "transition": 'none',
            "background": color,
            "background": "moz-radial-gradient (50% 50%, ellipse cover, transparent 0%, " + color + " 0%)",
            "background": "-webkit-radial-gradient(50% 50%, circle, transparent 0%, " + color + " 0%)",
            "background": "radial-gradient(circle at center, transparent 0%, " + color + " 0%)",
            "width": 0
        })
        self.$loader.fadeIn(0);
    }
});

这完全按照我想要的方式工作,除了,当我尝试为生产构建 dist 文件时,jshint 为 background 属性 抛出一个 duplicate key 错误,这使得感觉。我的问题是,如何在为所有不同浏览器设置背景渐变时防止出现此错误?

jsHint 是正确的,因为您的代码有缺陷。每次在对象中定义它时,您都会覆盖 background 键,因此只会分配最终值。我只能假设它对你有效,因为 radial-gradient 在你测试的浏览器中有效。

这是您遇到的问题的演示:

var foo = function(o) {
    Object.keys(o).forEach(function(key) {
        console.log(key); // note only 1 key is shown as it's overwritten
    })
    
    console.log(o.background); // shows the last value
}

foo({
    "background": 'red',
    "background": "moz-radial-gradient (50% 50%, ellipse cover, transparent 100%, red 5%))",
    "background": "-webkit-radial-gradient(50% 50%, circle, transparent 100%, red 5%)",
    "background": "radial-gradient(circle at center, transparent 100%, red 5%)"
})

要解决此问题,您需要调用 attr() 并将样式直接应用于元素。 css() 不能使用,因为它也会在您每次调用时覆盖 background 属性。

var style = [
    "background: " + color,
    "background: moz-radial-gradient (50% 50%, ellipse cover, transparent " + value + "%, " + color + " " + value + "%))",
    "background: -webkit-radial-gradient(50% 50%, circle, transparent " + value + "%, " + color + " " + value + "%)",
    "background: radial-gradient(circle at center, transparent " + value + "%, " + color + " " + value + "%)"
].join(';');

$(this).attr('style', style); 

我承认它很丑,但是没有真正的选择