设置对象中元素的样式

Set style of element from object

本文关键字:样式 元素 对象 设置      更新时间:2023-09-26


我在为对象中的元素设置样式时遇到问题。在第一个函数中,我用样式代码解析字符串

parseCheckingStyle: function(properties) {
    var propertiesList = {},
    tempArr=properties.split(/'s*;'s*/, this.length);
    tempArr.forEach(function(element, value, array){
        var splittedTempArr = element.split(/'s*:'s*/);
        propertiesList[splittedTempArr[0]] = splittedTempArr[1];
    });
    return propertiesList;
};

例如

parse('background: #ccc; color: #fff;')

返回

{background: "#ccc", color: "#000"}

然后,通过这个功能,我尝试设置这个类似对象的元素样式:

setCheckingStyle: function(selector, properties) {
    var propertiesList = this.parseCheckingStyle(properties);
    for (var key in propertiesList){
        selector.style.key = propertiesList[key];
    }
};

但风格不是背景。我该如何解决这个问题?

附言:我需要在没有jQuery 的情况下实现

它应该是selector.style[key]而不是selector.style.key。当您使用.时,属性名称是按字面意思使用的,而不是作为变量使用;您必须使用[]将其作为变量进行评估。

你显然已经知道了,因为你写的是propertiesList[key]而不是propertiesList.key