我想申请下面的图像作为背景图像,但我不能这样做。应用背景图像与动态CSS
这里是我的setbackground.php代码..
<?php
$header_tile_image_url = 'http://www.example.com/myimage.jpg';
?>
var css = 'body {background-color:#fff;background-image:url(<?php echo $header_tile_image_url; ?>)}';
var themeCssNode = document.getElementById('theme_css');
if (themeCssNode) {
themeCssNode.parentNode.removeChild(themeCssNode);
}
themeCssNode = document.createElement('style');
themeCssNode.type = 'text/css';
themeCssNode.id = 'theme_css';
document.getElementsByTagName('head')[0].appendChild(themeCssNode);
if (themeCssNode.styleSheet) {
themeCssNode.styleSheet.cssText = css;
} else {
var cssText = document.createTextNode(css);
themeCssNode.appendChild(cssText);
}
以上的JavaScript将取代样式表,并应用新的。 问题在于应用背景图像。下面
是我的html代码 ..需要
<html>
</head> <title> test program </title>
<style id="theme_css" type="text/css">
body {background-color:blue;font:13px arial,sans-serif;}
</style>
</head>
</body>
<script src="setbackground.php"> </script>
<h1> This is my test page </h1>
</body>
</html>
查看浏览器对“setbackground.php”的请求。 http://jsfiddle.net/bnEnn/1/ 你的代码似乎很好。 – reinder 2013-02-09 11:14:28
Reinder ...当我们把直接的图像链接,然后它工作正常..感谢那... body(background-color:#fff; background-image:url(http://placehold.it/100x100)}但这里的图像是动态链接,我正在从数据库中读取并放入php变量并将其传递给javascript body {background-color:#fff; background-image:url(<?php echo $ header_tile_image_url;?>)然后它会不应用背景图像其实JavaScript本身不会执行不知道为什么...有任何想法? – SmartDev 2013-02-09 11:23:06
如果您在浏览器窗口中打开setbackground.php,返回什么?另外请注意,您可能希望将其设置为返回“text/javascript”作为内容类型。 – reinder 2013-02-09 11:25:16