【发布时间】:2012-11-02 01:35:05
【问题描述】:
我正在编写一个函数来在明暗之间切换身体背景,包括平铺图像和备用背景颜色。在 index.html 中,我的 body 标签是:
<body style="background-color:#111111; background-image:url('dvsup.png');">
看来我要通过javascriptwithin index.html把我想改变的样式,不然不行。至少,在 IE9 中没有。
这是我 script.js 中的代码 sn-p:
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 中的背景图像将更改为“dvsupw .png”调用“light()”,但不会变回来。
我是否遗漏了一些明显的东西?这怎么不行?
如果我不清楚,请告诉我。
谢谢。阿尔。
【问题讨论】:
-
你能把
console.log(document.body.style.backgroundImage)的输出贴在IE和Chrome中吗? -
尝试用单引号 (
') 替换双引号 ("),反之亦然 -
尝试
(b?t:f)而不是(b)?t:f,也可以在某些浏览器中将域和路径放入图像的url中。 -
您为什么要切换课程并设置值?您应该只切换一个类并在样式表中包含样式!
-
@epascarello 是绝对正确的,我不敢相信我以前没想过这样做。在“.lit”和“.unlit”类之间切换 之后,代码在 IE9 和 Chrome 中都能实现梦想。谢谢。
标签: javascript css cross-browser styles background-image