JQuery - 基于时间条件的运动图像

JQuery - moving images based on time conditional

我在编写一个 JQuery 函数时遇到问题,该函数将在下午 6 点之前将太阳图像从左下角沿对角线移动到右上角,并且一旦时间变量达到下午 6 点,就会制作一个月亮图像斜升到右上角,而太阳落回原来的位置。感谢您的帮助。

<script type="text/JavaScript">    

var objDate = new Date();
var time = objDate.getHours();

        $(document).ready(function() {
           if (time < 18)
                $("sun").animate({
                  'left' : "+=30px", 
                  'top' : "-=30px" 
                }, 5000);
                $('moon').animate({
                  'left' : "-=30px", 
                  'top' : "+=30px" 
                }, 5000);

           if (time > 18)
                $("sun").animate({
                  'left' : "-=30px", 
                  'top' : "+=30px" 
                }, 5000);
                $("moon").animate({
                  'left' : "+=30px", 
                  'top' : "-=30px" 
                }, 5000);
            });

</script>



<style type="text/css">
        #citiscape{
            position: absolute;
            bottom: 0px;
            left: 0px;
            z-index: 5;
            background-image: url(city.png);
            background-repeat: repeat-x;
            width: 100%;
            height: 300px;
        }

        #sun {
            width: 300px;
            height: 300px;
            position: absolute;
            left: 250px;
            top: 400px;
            z-index: 2;
            background-image: url(sun.jpg)
        }

        #moon {
            width: 300px;
            height: 300px;
            position: absolute;
            left: 500px;
            top: 650px;
            z-index: 3;
            background-image: url(moon.png); 
            background-size: cover;
            border: 1px solid green;
        }                   
</style>
</head>

<body>
<div id="citiscape"></div>
<div id="sun"></div> 
<div id="moon"></div>
</body>

您无法制作动画,因为您的 jQuery 选择器有误。它正在等待 CSS 选择器。

 $("sun").animate //"sun" is not a CSS selector

 $("#sun").animate //"#sun" (ID) is the correct one.