如何通过javascript更好地将复杂样式写入元素?

时间:2016-03-14 10:01:40

标签: javascript html css dom

我以前使用jQuery,最近我开始使用vanilla Javascript,我从这里开始有点新鲜。

鉴于我有以下代码,如何将其构建为更清晰的代码?请指教。

我有理由将每个背景样式分开,而不是使用background本身。我也有一些理由说明为什么不使用CSS。

我的实现是在HTML中设置data标记的设置,并使用javascript来渲染其样式而不是使用CSS。

const section_bg = document.querySelectorAll('.js-section-bg');

for (let i = 0; i < section_bg.length; i++) {
    var this_image = section_bg[i];

    let settings = {
        url: this_image.dataset.bgSrc,
        position: this_image.dataset.bgPosition,
        color: this_image.dataset.bgColor,
        size: this_image.dataset.bgSize,
        repeat: this_image.dataset.bgRepeat
    }

    this_image.style.backgroundRepeat = settings.repeat;
    this_image.style.backgroundSize = settings.size;
    this_image.style.backgroundColor = settings.color;
    this_image.style.backgroundPosition = settings.position;
    this_image.style.backgroundImage = "url('" + settings.url + "')";
}

3 个答案:

答案 0 :(得分:2)

好吧,你可以这样写:

&#13;
&#13;
function $(sel) {
    return Object.assign(
        [].slice.call(document.querySelectorAll(sel), 0),
        {
            css: function (props) {
                this.forEach(function (el) {
                    Object.keys(props).forEach(function (k) {
                        el.style[k] = props[k];
                    });
                });
            }
        }
    );
}

$('div').css({
    backgroundColor: 'red',
    border: '3px solid blue'
});
&#13;
<div>A</div>
<div>B</div>
<div>C</div>
<div>D</div>
&#13;
&#13;
&#13;

这是否有意义是另一个问题......

答案 1 :(得分:1)

Array.from(document.querySelectorAll('.js-section-bg')).forEach(image => {
    const style = image.style,
          data = image.dataset;
    style.backgroundColor = data.bgColor;
    style.backgroundRepeat = data.bgRepeat;
    style.backgroundSize = data.bgSize;
    style.backgroundPosition = data.bgPosition;
    style.backgroundImage = `url('${data.bgSrc}')`;
});

答案 2 :(得分:1)

使用ES6模板字符串:

this_image.style.cssText = `background:${settings.color} url(${settings.url}) ${settings.position} / ${settings.size} ${settings.repeat}`;

当然,您可以不使用ES6模板字符串并手动连接字符串和变量。

Background shorthand syntax