style.setProperty()方法似乎不起作用

时间:2018-03-09 10:21:20

标签: javascript

我是stackoverflow的新手,我希望我能以正确的方式描述我的问题。我想使用setProperty方法向一个元素添加css样式,我遇到了一些问题。似乎只添加了一些属性而其他属性没有,我无法弄清楚原因。在这种情况下,它只渲染'background-size'属性 - 当我评论该行代码时,它呈现一个没有任何内联样式的简单div。我很感激你的帮助。谢谢。这是我的代码:

    const Img = new Image();
    Img.src = "example.jpg";

    const div = document.createElement('div');
    console.log("Simple div: ", div); //<div style="background-size: cover;"></div> ???

    div.style.setProperty('width', 400);
    console.log("Adding width: ", div); //<div style="background-size: cover;"></div>

    div.style.setProperty('height', 300);
    console.log("Adding height", div); //the same as above

    div.style.setProperty('background-image', Img.src);
    console.log("Adding bg image:", div); //the same as above

    div.style.setProperty('background-size', 'cover');
    console.log(div); //<div style="background-size: cover;"></div>

    document.querySelector('body').appendChild(div);

1 个答案:

答案 0 :(得分:2)

您在CSS规则中插入了无效值:

  

您需要在设置元素widthheight时指定值的单位。 See this documentation.

.setProperty('width', 400);

应该是

.setProperty('width', '400px');

  

您需要指定您作为background-image值传递的内容确实是url( ... )的网址。 See this documentation

.setProperty('background-image', Img.src);

应该是

.setProperty('background-image', 'url(' + Img.src + ')');

const Img = new Image();
Img.src = "https://www.gravatar.com/avatar/c64594c112836c735bf0148a0557795a?s=32&d=identicon&r=PG&f=1";

const div = document.createElement('div');
console.log("Simple div: ", div);

div.style.setProperty('width', '400px');
console.log("Adding width: ", div);

div.style.setProperty('height', '300px');
console.log("Adding height", div)

div.style.setProperty('background-image', 'url(' + Img.src + ')');
console.log("Adding bg image:", div); 

div.style.setProperty('background-size', 'cover');
console.log(div);

document.querySelector('body').appendChild(div);