簡體   English   中英

應用具有動態CSS的背景圖像

[英]Applying a background image with dynamic 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>

您的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; ?>)";

這對您有用嗎?

嘗試這個

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

因此,問題在於執行代碼后圖像無法加載? 您是否嘗試過在輸出任何內容之前將header("Content-type: text/javascript")包含在setbackground.php文件中?

<?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');
// ....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM