缓存CSS属性名称的通用函数

时间:2018-10-31 09:00:02

标签: javascript 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") },
}

2 个答案:

答案 0 :(得分:0)

一种选择是使用Proxy,它可以检测您要在对象上访问的属性字符串,并根据该字符串执行自定义操作。使用该字符串,然后可以检查它是否在style中存在,使用括号表示法将其分配给对象,并与webkit串联:

const js = new Proxy({}, {
  get: (obj, prop) => {
    if (prop === 'testElementStyle') {
      obj.testElementStyle = document.createElement('div').style;
      return this.testElementStyle;
    }
    this[prop] = prop in obj.testElementStyle
      ? prop
      : 'webkit' + prop.replace(/^./, char => char.toUpperCase());
    return this[prop];
  }
});

答案 1 :(得分:0)

您有两个选择:

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

  2. 使用Proxy(ES2015 +)

CertainPerformance has Proxy covered一样,这是使用函数的方式:

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");