javascript - document.body.style.backgroundImage 无法跨浏览器工作

标签 javascript css cross-browser styles background-image

我正在编写一个函数来在明暗之间切换 body 背景,包括平铺图像和备用背景颜色。在 index.html 中,我的 body 标签是:

<body style="background-color:#111111; background-image:url('dvsup.png');">

看来我必须将我想通过javascript 更改的样式放在index.html 中,否则它不起作用。至少,不是在 IE9 中。

这是我的 script.js 中的代码片段:
function _(el){return document.getElementById(el);}
// this just acts as shorthand

//here's the problematic function:
function light(){
    _("lights").className=
    (_("lights").className==="deselected")?
    "selected":"deselected";

    document.body.style.backgroundColor=
    (document.body.style.backgroundColor==="#111111")?
    "#EFEFEF":"#111111";

    document.body.style.backgroundImage=
    (document.body.style.backgroundImage==="url('dvsup.png')")?
    "url('dvsupw.png')":"url('dvsup.png')";}

这一切在工作计算机上的 IE9 中都可以完美运行。当按钮调用“light()”时,它会更改背景图像和颜色以及按钮本身的类。在 Chrome 和 Chromium(在家里)中,它分崩离析。将 className 从“selected”更改为“deselected”有效,但其余部分无效。

奇怪的是,如果我将“===”标识符更改为“=”用于“style.backgroundColor”和“style.backgroundImage”的分配器,则在 Chrome 中,在调用“light()”时,背景图像将更改为“dvsupw.png” ,但不会变回来。

我错过了一些明显的东西吗?这怎么行不通?

如果我还不清楚,请告诉我。

谢谢。阿尔。

最佳答案

为什么不尝试使用 CSS 设置背景颜色,然后使用调用它的 jQuery 制作一个函数。像这样的东西:

background-color:#111;
var color = $(this).css("background-color");
/* here put your conditional for the color */

关于javascript - document.body.style.backgroundImage 无法跨浏览器工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13188065/

相关文章:

internet-explorer - X-下载-选项 : noopen equivalent

silverlight - Silverlight 中的并发连接数

css - 跨浏览器 css 规则 : Mozila, chrome、safari 和 css2 与 css3

javascript - 如何更新位于asp.net iframe之外的ajax updatepanel

javascript - 如何使用 AsyncStorage 仅显示一次应用程序简介(首次运行时) - React Native

javascript - 尝试在 ReactJS 中针对对象内、对象内的 JSON 对象...

javascript - 小书签和 CoffeeScript

html - 如何显示浏览器屏幕宽度?

不使用 url 的 CSS 背景

javascript - 内联(不是内联 block )行为元素的最小宽度