我正在编写一个函数来在明暗之间切换 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/