简体   繁体   English

如何使用javascript动态传递background:url到css?

[英]How to pass background:url dynamically using javascript to css?

See the css below and I would like to change the "background:url" part dynamically using javascript. 请参阅下面的CSS,我想使用javascript动态更改“background:url”部分。

div{
    background: url('pinkFlower.jpg') no-repeat fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    width:100vw;
    height:100vh;
    top:0;
    left:0;
    float:left;
}

I tried the same by passing below javascript 我通过传递下面的javascript尝试了同样的方法

document.querySelector('div').style.background= "url('pinkFlower.jpg') no-repeat fixed";

and this results against my purpose of the original css. 这导致了我原来的CSS的目的。

Can someone help me fixing this? 有人可以帮我解决这个问题吗?

Thanks in advance. 提前致谢。

I think this should work : 我认为这应该有效:

document.querySelector('div.image').style.backgroundImage = 'url("your/url/to/the/file")';

Edit : Trick : if you're on Chrome, launch webdev panel (F12) and in the console write console.log(document.querySelector('div.image').style) 编辑:诀窍:如果你在Chrome上,启动webdev面板(F12)并在控制台中编写console.log(document.querySelector('div.image').style)

You will get all attributes of the "style" object, which you can then change as you want 您将获得“样式”对象的所有属性,然后您可以根据需要进行更改

To understand what's going on here, you need to understand two things: CSS specificity and CSS background- properties. 要了解这里发生了什么,您需要了解两件事:CSS特异性和CSS background-属性。


1: CSS Specificity 1:CSS特异性

The primary problem you are having here is that using .style=[something] in Javascript will write your new styles to the HTML style="[something]" attribute. 你在这里遇到的主要问题是在Javascript中使用.style=[something]会将你的新样式写入HTML style="[something]"属性。 It does not overwrite the browser's cached version of the CSS, and therefore, all rules pertaining to the property you are changing are simply ignored and not overwritten . 不会覆盖浏览器的CSS缓存版本,因此,所有与您正在更改的属性相关的规则都会被忽略不会被覆盖

CSS also reads rules in order, from least specific to most specific, from top to bottom. CSS还按顺序读取规则,从最不具体到最具体,从上到下。 Every time it finds a new rule for an existing property, it disregards the old one and uses the new one. 每次为现有属性找到新规则时,它都会忽略旧规则并使用新规则。

With that in mind, let's take a look at: 考虑到这一点,让我们来看看:

2: Background- Properties 2:背景属性

In CSS, there are multiple properties that handle background , such as: 在CSS中,有多个属性可以处理background ,例如:

  • background:
  • background-size:
  • background-position:
  • etc. 等等

Each of these properties will only affect ONE property of the background settings; 这些属性中的每一个都只会影响后台设置的一个属性; the exception to this rule is the catch-all background: property. 这个规则的例外是catch-all background: property。

By setting the background: property, you overwrite ALL background settings, including ones you don't specify . 通过设置background:属性,可以覆盖所有背景设置, 包括未指定的设置 Now in your CSS, you have written other background- properties after that catch-all background: property. 现在在你的CSS中,你已经在catch-all background: property之后写了其他的background- -properties。 Those will cause CSS to ignore the specific rules you set in the catch-all property. 这些将导致CSS忽略您在catch-all属性中设置的特定规则。

BUT! 但!

When you set the .style to use the background: property, you are inserting a whole new set of CSS rules that are more specific than the previous ones. 当您将.style设置为使用background:属性时,您将插入一组比以前更具体的新CSS规则。 This means that CSS will read this new property last, and since it is the catch-all, it will ignore ALL of the previous rules you just set up; 这意味着CSS将最后读取这个新属性,因为它是catch-all,它将忽略您刚刚设置的所有先前规则; in particular, it is ignoring your background-size property. 特别是,它忽略了你的background-size属性。

To fix this, make sure that you set each of these individually and do not use the catch-all property. 要解决此问题,请确保单独设置其中每个,并且不要使用catch-all属性。

Eg use background-image , background-repeat , and background-position instead of background: . 例如,使用background-imagebackground-repeatbackground-position而不是background:

document.getElementById("myDiv").style.backgroundImage = "url(/img/someImage.jpg)";

You can use the background: property, but it will require you to re-set all of the other background- properties that you set in the original CSS via Javascript. 可以使用background:属性,但它需要您重新设置通过Javascript在原始CSS中设置的所有其他background-属性。

The context is not completely clear, but the selector you are using in js is "div.image" and the css is just "div". 上下文并不完全清楚,但你在js中使用的选择器是“div.image”而css只是“div”。 The selectors must match. 选择器必须匹配。 Make sure either the css uses "div.image" or the js uses "div". 确保css使用“div.image”或js使用“div”。

See this JSFiddle . 看到这个JSFiddle You just need to replace the URL image and not the other properties. 您只需要替换URL图像而不是其他属性。

This is the line that works: 这是有效的线:

document.querySelector('div').style['backgroundImage'] = "url('your/image.png')"

When you use background it overrides all of the background properties, including background-size. 使用背景时,它会覆盖所有背景属性,包括background-size。

you want to use the following line if you want to retain background-size: 如果要保留背景大小,则要使用以下行:

document.querySelector('div').style.backgroundImage= "url('pinkFlower.jpg') no-repeat fixed";

if this wasn't your problem please explain yourself better 如果这不是你的问题,请更好地解释自己

Try utilizing .textContent , String.prototype.match() , String.prototype.split() , String.prototype.replace() to replace text between url(' , ') of style element 尝试使用.textContentString.prototype.match()String.prototype.split()String.prototype.replace()来替换style元素的url('')之间的文本

 var style = document.getElementsByTagName("style")[0]; var url = new RegExp(style .textContent .match(/url\\(\\'(.*)\\'\\)/)[0] .split(/url\\(\\'|\\'\\)/)[1] ); style.textContent = style .textContent .replace(url , "http://lorempixel.com/100/100/sports") 
 div { background: url('http://lorempixel.com/100/100/nature') no-repeat fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; width: 100vw; height: 100vh; top: 0; left: 0; float: left; } 
 <div></div> 

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

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