使用Javascript设置div标签的大小不起作用

时间:2017-09-16 09:38:39

标签: javascript html css background-size

我需要在动画期间更改背景图片的大小,但它不起作用。

以下是我的代码的简单版本:



document.querySelector("#Box").backgroundSize='cover';

#Box {
		background-image: url(https://beebom-redkapmedia.netdna-ssl.com/wp-content/uploads/2016/01/Reverse-Image-Search-Engines-Apps-And-Its-Uses-2016.jpg);
		width: 220px;
		height: 220px;
    }

  <div id="Box"></div>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:0)

您应定位.style

&#13;
&#13;
document.querySelector("#Box").style.backgroundSize='cover';
&#13;
#Box {
		background-image: url(https://beebom-redkapmedia.netdna-ssl.com/wp-content/uploads/2016/01/Reverse-Image-Search-Engines-Apps-And-Its-Uses-2016.jpg);
		width: 220px;
		height: 220px;
    }
&#13;
  <div id="Box"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您在查询选择器中缺少.style声明

&#13;
&#13;
document.querySelector("#Box").style.backgroundSize='cover';
&#13;
#Box {
		background-image: url(https://beebom-redkapmedia.netdna-ssl.com/wp-content/uploads/2016/01/Reverse-Image-Search-Engines-Apps-And-Its-Uses-2016.jpg);
		width: 220px;
		height: 220px;
    }
&#13;
<div id="Box"></div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

从你的js中遗漏style ......

&#13;
&#13;
document.querySelector("#Box").style.backgroundSize='cover';
&#13;
#Box {
		background-image: url(https://beebom-redkapmedia.netdna-ssl.com/wp-content/uploads/2016/01/Reverse-Image-Search-Engines-Apps-And-Its-Uses-2016.jpg);
		width: 220px;
		height: 220px;
    }
&#13;
<div id="Box"></div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

#Box元素没有backgroundSize属性。您应该只引用它的style属性,然后再引用backgroundSize

document.querySelector("#Box").style.backgroundSize = 'cover'