首页 > 解决方案 > 用于缓存 css 属性名称的通用函数

问题描述

我创建了这个对象来根据浏览器获取 css 属性名称。例如,js.transition 将根据需要返回“webkitTransition”或“transition”。所有值都被缓存,即。第一次引用将在 testElementStyle 对象中查找值,重复引用将返回缓存的值。

const js = {
    get testElementStyle() {
        delete this.testElementStyle;
        return this.testElementStyle = document.createElement('div').style;
    },
    get transition() {
        delete this.transition; 
        return this.transition = "transition" in this.testElementStyle ? "transition" : "webkitTransition" 
    },
    get transform() {
        delete this.transform; 
        return this.transform = "transform" in this.testElementStyle ? "transform" : "webkitTransform" 
    },
    get userSelect() { 
        delete this.userSelect 
        return this.userSelect = "userSelect" in this.testElementStyle ? "userSelect" : "webkitUserSelect" }    
}

如您所见,每个属性的缓存代码都是重复的。理想情况下,我想创建一个接受道具名称并完成其余工作的通用函数。

例如

const cache = prop => alt => {
    delete this[prop];
    return this[prop] = prop in this.testElementStyle ? prop : alt;
}  

...这当然行不通,我有点卡住了,请帮忙!


这是我在阅读您的评论之前所做的。有了你的建议,我现在可以把它提升到一个新的水平。感谢大家!

const testElementStyle = document.createElement('div').style;
function cache(prop, alt) {
    delete this[prop];
    return this[prop] = prop in testElementStyle ? prop : alt;
}
const js = {
    get transition() { return cache.call(this, "transition", "webkitTransition") },
    get transform() { return cache.call(this, "transform", "webkitTransform") },
    get userSelect() { return cache.call(this, "userSelect", "webkitUserSelect") },
}
const css = {
    get transform() { return cache.call(this, "transform", "-webkit-transform") },
}

标签: javascriptcss

解决方案


你有两个选择:

  1. 使用函数并传入字符串

  2. 使用Proxy(ES2015+)

由于CertainPerformance 已经覆盖了代理,因此您可以使用函数来执行此操作:

const js = {
    get testElementStyle() {
        return this.testElementStyle = document.createElement('div').style;
    },
    get(name) {
        return this[name] = name in this.testElementStyle ? name : "webkit" + name.substring(0, 1).toUpperCase() + name.substring(1);
    }
};

用法:

js.testElementStyle(); // It's unclear to me why you make this setup call necessary
const transform = js.get("transform");

推荐阅读