[英]How to change a background that is declared in .css not html
USING JAVASCRIPT, NO JQUERY Hi all, I know this is a basic one but I am hitting a dead end. 使用JAVASCRIPT,没有JQUERY大家知道,我知道这是基本的,但是我快要死了。 I want to change a background image that is in the
.css
, not the html
so I cant give it an id
. 我想更改
.css
的背景图像,而不是html
中的背景图像,因此我不能给它提供一个id
。 I managed to remove the image using: 我设法使用以下方法删除了图像:
var headerImg = document.getElementById('header').background = 'none';
And tried : 并尝试:
var headerImg = document.getElementById('header').background = 'images/new-header.jpg;
But that did'nt work. 但这没有用。 I have no idea how to change the Image, and in the dev tools the url does not even change when I try to run my code Any help would be great, Thanks.
我不知道如何更改图像,并且在开发工具中,当我尝试运行代码时,URL甚至都不会更改。非常感谢,谢谢。
You're close. 你近了 You're just off on the syntax slightly...
您只是略微了解了语法...
document.getElementById("header").style.backgroundImage = "url(images/new-header.jpg)";
It's a style attribute you're changing, so you need .style
and then you use the CSS attribute name, but remove hyphens and camelCase the attribute name, so .backgroundImage
. 这是您要更改的样式属性,因此需要
.style
,然后使用CSS属性名称,但要删除连字符和camelCase属性名称,即.backgroundImage
。
Can you try this 你可以试试这个吗
var element = document.getElementById('content'); element.style.backgroundImage = "url('https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSzOpUTzDIq2yutn75PQTLcHhJ06MTZPsV_V-0M918xKUhAqMxE')";
<div> <p>this is unchanged</p> <p id="content">backgroud wiil be cange</p> <div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.