单击图像时背景图像会更改

Background image change when clicking a image

本文关键字:图像 背景 单击      更新时间:2023-09-26

所以我正在尝试根据单击的图标更改以下页面的背景,但我不确定我的代码出了什么问题!这只是一个测试页面(请原谅奇怪的代码,但我在实际站点本身中需要它!

<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
 body   {
background: url('<?php echo $_GET['image']; ?>';
}

</style>

<script>
    function showWeather(Weather) {
     //alert(Weather);
        myform.weather.value=Weather;
    //  alert(Weather);
    // ._Weather
        myform.submit();

}
</script>

<link href="teststyle.css" rel="stylesheet" type="text/css">
</head>
<body background="images/gradientsky.jpg"> 
<div id="weather">
<ul id="nav-reflection">
<form method="post" action="cloudy_name.php" id="myform">
    <li class="button-color-1"><a href="cloudy_name.php?image=images/cloudysky.png" onclick="showWeather('cloudy');" title="My fancy link"><img src="images/cloudybubble.png" width="211" height="180" align="left"></a></li> 
    <input type="hidden" name="weather" value="whatever">
</form>
</ul>
</div>
</body>
</html>

你在这里有几个问题,我会尝试解决它们:

<form method="post" action="cloudy_name.php" id="myform">
        <li class="button-color-1"><a href="javascript:showWeather('cloudysky')" onclick="changeBgImage(images/cloudysky)" title="My fancy link"><img src="images/cloudybubble.png" width="211" height="180" align="left"></a></li>
</form>
  1. 您缺少"ul"包装器。列表项不能单独存在。
  2. 你说的是showWeather('多云')。"Cloudysky"不是一个完整的文件名,所以也许它是Cloudysky.jpg?
  3. 用户
  4. 正在单击链接并被发送到另一个页面,因此一旦用户返回,您使用javascript在此处所做的任何更改都不会保留。
  5. document.getElementById(test) 需要引用一个字符串,就像 document.getElementById("test")

一试并报告。

你的 changeBgImage 函数没有通过字符串 'image' 传递

试试这个:

    <script type="text/javascript">
        function changeBgImage (image) { // added Image
            var element = document.getElementById('test');
            element.style.backgroundImage = "url('"+image+"')"; // added single qoutes around image
            // Took out window.location - see comments below for explanation
            return false;// Added to stop Link execution
        }
    </script>
</head>
<body>
<div id="test">
    <form method="post" action="cloudy_name.php" id="myform">
        <li class="button-color-1"><a href="#" onclick="showWeather('cloudy'); changeBgImage('images/cloudysky.png');" title="My fancy link"><img src="images/cloudybubble.png" width="211" height="180" align="left"></a></li>
    </form>
</div>

我将所有javascript函数添加到onclick中,包括showWeatherchangeBgImage

请参阅下面的评论。

想法:在链接上创建一个指向 PHP 文件的链接。 类似 chg_bg.php?图像=多云

在 php 文件上,创建一些代码来设置背景

<style>
    background: url('<php echo $_GET['image']; ?>';
</style>