简体   繁体   English

使用Java脚本更改背景图像CSS

[英]Changing a Background-image CSS with Javascript

I have a Wordpress site with a background in the header inside of a class. 我有一个Wordpress网站,其背景在类的标题内。

I'm tring to write a bit of JS to change this background image depending on a hashtag. 我想写一些JS来根据主题标签更改此背景图片。 The Hashtag script is working but the change BG bit isn't - please help... :-( Hashtag脚本正在运行,但更改BG位不起作用-请帮助... :-(

The script I've writen is: 我写的脚本是:

  document.getElementsByClassName("eut-bg-image").style.backgroundImage = "url(https://boutiqueballer.com/wp/wp-content/uploads/2017/10/chanel.jpg)";
})();

getElementsByClassName yields a collection of elements. getElementsByClassName产生元素的集合。 The individual elements in the collection have the style property, not the collection itself. 集合中的各个元素具有style属性,而不是集合本身。 If you are targeting just one element, you can access it by index: 如果您仅定位一个元素,则可以按索引访问它:

document.getElementsByClassName('eut-bg-image')[0].style.backgroundImage = ...;

If you are targeting several elements, you may iterate over them: 如果您要定位多个元素,则可以对其进行迭代:

var elements = document.getElementsByClassName('eut-bg-image');
for(var i = 0; i < elements.length; i++)
   elements[i].style.backgroundImage = ...;

Alternatively, you may use document.querySelector , depending on which level of browser compatibility you need. 或者,您可以使用document.querySelector ,具体取决于所需的浏览器兼容性级别。 You can then distinguish between document.querySelectorAll if you want a collection, or docment.querySelector if you want only the first match. 然后,您可以在需要集合的情况下区分document.querySelectorAll ,或者在仅需要第一个匹配项的情况下区分docment.querySelector Accepts a CSS selector: 接受CSS选择器:

document.querySelector('.eut-bg-image').style.backgroundImage = ...;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM