PHP包含在DIV样式背景中

时间:2014-05-28 13:37:47

标签: javascript php html

我有一个每天都在变化的旋转图像,我试图将它作为DIV的背景图像,这样我就可以在它上面有一个菜单了。出于某种原因,它只显示包含文件中的所有信息,而不是显示每日图像?

<div styles="background-image: url(<?php include('includes/promotions.php'); ?>)">MENU</div>

在包含文件中:

<SCRIPT LANGUAGE="JavaScript">
today = new Date();
day = today.getDay();
arday = new Array("images/daily-offers/sunday.png", "images/daily-offers/monday.png", "images/daily-offers/tuesday.png", "images/daily-offers/wednesday.png", "images/daily-offers/thursday.png", "images/daily-offers/friday.png", "images/daily-offers/saturday.png");
document.write("<img src='"+arday[day]+"'>");
</script>`

我对此很新,但我很感激帮助!

4 个答案:

答案 0 :(得分:1)

您正在尝试将javascript放入div的style属性中,这是不可能的。您需要让PHP代码提供文件名而不是使用include,或者您需要创建div给它一个id使用javascript(在div的样式之外)来更改背景图像。 / p>

<div id='changeme'>Menu</div>

<SCRIPT LANGUAGE="JavaScript">
    today = new Date();
    day = today.getDay();
    arday = new Array("images/daily-offers/sunday.png", "images/daily-offers/monday.png", "images/daily-offers/tuesday.png", "images/daily-offers/wednesday.png", "images/daily-offers/thursday.png", "images/daily-offers/friday.png", "images/daily-offers/saturday.png");
    //ASSUMING YOU HAVE JQUERY
    $('#changeme').css('background-image',arday[day]);
</SCRIPT>

或者只是使用php:

<?php
$arday = array("images/daily-offers/sunday.png", "images/daily-offers/monday.png", "images/daily-offers/tuesday.png", "images/daily-offers/wednesday.png", "images/daily-offers/thursday.png", "images/daily-offers/friday.png", "images/daily-offers/saturday.png");
$day = date('w');
?>
<div styles="background-image: url('<?php echo $arday[$day]; ?>')">MENU</div>

或者,如果图像的命名约定始终相同,则可以执行以下操作:

<div styles="background-image: url('images/daily-offers/<?php echo strtolower(date('l')); ?>.png')">MENU</div>

答案 1 :(得分:1)

您可以像这样设置backgroundImage:

document.getElementById("mymenu").style.backgroundImage="url(...)";

您的代码可能是这样的:

<div id="mymenu">MENU</div>

<SCRIPT LANGUAGE="JavaScript">
today = new Date();
day = today.getDay();
arday = new Array("images/daily-offers/sunday.png", ...);
document.getElementById("mymenu").style.backgroundImage="url('"+arday[day]+"')";
</script>`

答案 2 :(得分:1)

你不能在类似的属性中执行javascript。

您可以尝试此操作 - 将includes/promotions.php文件的内容更改为以下内容:

<?php
$day = strtolower(date('l'));
echo '<img src="images/daily-offers/' . $day . '.png">';
?>

此外,div上的属性应为style,而不是styles

答案 3 :(得分:-2)

我不会用PHP来做那件事。 我会在您正在显示div的页面上显示以下javascript代码。

<div id="bgdiv">MENU</div>

<SCRIPT LANGUAGE="JavaScript">

    today = new Date();
    day = today.getDay();
    arday = new Array("images/daily-offers/sunday.png", "images/daily-offers/monday.png", "images/daily-offers/tuesday.png", "images/daily-offers/wednesday.png", "images/daily-offers/thursday.png", "images/daily-offers/friday.png", "images/daily-offers/saturday.png");
    document.getElementById('bgdiv').style.backgroundImage = "url(' + arday[day] + ')";

</script>