2013-02-09 98 views
0

我想申请下面的图像作为背景图像,但我不能这样做。应用背景图像与动态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> 
+0

查看浏览器对“setbackground.php”的请求。 http://jsfiddle.net/bnEnn/1/ 你的代码似乎很好。 – reinder 2013-02-09 11:14:28

+0

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

+0

如果您在浏览器窗口中打开setbackground.php,返回什么?另外请注意,您可能希望将其设置为返回“text/javascript”作为内容类型。 – reinder 2013-02-09 11:25:16

回答

0

你的PHP代码都可以在PHP标记中包含。

<?php 
    $header_tile_image_url = 'http://www.example.com/myimage.jpg'; 
?> 

http://www.javascriptkit.com/javatutors/setcss3properties.shtml

document.body.style.backgroundColor = "#fff"; 
document.body.style.backgroundImage = "url(<?php echo $header_tile_image_url; ?>)"; 

这是否对你的工作?

+0

Banath..no这不工作已经尝试...谢谢你的回答 – SmartDev 2013-02-09 11:00:29

+0

你有什么问题到底是什么? “应用背景图像时出现问题”对我而言并不清楚。 – Banath 2013-02-09 11:03:10

+0

我在问题中增加了更多细节..请看看 – SmartDev 2013-02-09 11:05:29

0

试试这个

body 
{ 
background: url(../Image/bg.jpg) #10a5d3; 
} 
+0

Pawan CSS不是问题,但当我改变使用JavaScript的样式表,然后它是问题.. – SmartDev 2013-02-09 11:06:40

0

那么,问题是执行代码时图像不加载?在输出任何东西之前,您是否尝试过在setbackground.php文件中包含header("Content-type: text/javascript")代码?

<?php 
    header("Content-type: text/javascript"); 
    $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'); 
// .... 
+0

闪闪发光..是我已经这样做,但仍然问题... – SmartDev 2013-02-09 12:19:02

+0

您的代码适用于我(并没有标题(“内容...”))。也许这可能是一个服务器配置问题? – megatxi 2013-02-09 13:03:55