首页 > 解决方案 > 如何使图像从屏幕上掉下来?

问题描述

我有这段代码允许我使用javascript在用户光标旁边放置一个随机图像,并使用CSS设置样式。我希望图像在几秒钟后从页面上掉下来,我的第一个想法是动画位置,但显然这是不可能的?

我怎么能做到这一点?这是我的 javascript 和 CSS 代码

Javascript

<script>

var myPix = new Array("/img/portfolio/30day.jpg", "/img/portfolio/animationposter.jpg","/img/portfolio/beetle.jpg","/img/portfolio/board.jpg","/img/portfolio/cyanotype.jpg","/img/portfolio/dissent.jpg")
document.addEventListener("click", showCoords);

function showCoords(event)
{

var randomNum = Math.floor(Math.random() * myPix.length);
var yourImage = document.createElement("img");
yourImage.src = myPix[randomNum] ;
yourImage.classList.add("mystyle");
yourImage.style.cssText = " width:360px;height:auto;position:fixed;top:" + event.clientY + "px;left:" + event.clientX + "px;";

document.body.appendChild(yourImage);
}
jQuery.fn.reverse = [].reverse;
</script>

CSS

.mystyle {
border-radius: 20px;
box-shadow: 0px 0px 10px 0 rgba(0, 0, 0, 0.1);
z-index: -2;
width: 360px;
height: auto;
position: fixed;


}

标签: javascripthtmlcss

解决方案


首先创建一个图像数组,以便您可以轻松访问所有图像。每当您创建图像时,将其推送到数组:

var images = [];
function showCoords(event)
{

var randomNum = Math.floor(Math.random() * myPix.length);
var yourImage = document.createElement("img");
yourImage.src = myPix[randomNum] ;
yourImage.classList.add("mystyle");
yourImage.style.cssText = " width:360px;height:auto;position:fixed;top:" + event.clientY + "px;left:" + event.clientX + "px;";
images.push([yourImage,0,0]); // this line is where we add the image. 
//In the same sub-array, put a number, 0, to store the image's age, and a velocity, 0, to make the physics look good. These will be used later.
document.body.appendChild(yourImage);
}

为了使您的图像动画化,您需要设置某种动画循环并在 a 中调用它setInterval

animate = function(){}
setInterval(animate,5); // choose whatever interval you want. Here, it is called every 5 milliseconds

在 animate 函数中,我们需要添加逻辑来改变每个图像的位置:

animate = function(){
   for(image of images){ // loop over all elements of our array
      image[1] += 1; //increase the age
      if(image[1] > 400){ //if old enough, fall
         image[2] += 0.1; //accelerate, tweak this value to change how strong gravity is
         currentTop = parseFloat(image[0].style.top.replace("px","")); // get the current y position
         currentTop += image[2]; //move
         newTop = String(currentTop) + "px"; //change back to string
         image[0].style.top = newTop; //set the attribute

         if(newTop > document.documentElement.clientHeight){ //if off-screen, remove it
         document.body.removeChild(image[0]);
         images.splice(images.indexOf(image),1); //remove from array
         }
      }
   }
}

现在你应该可以走了。我在 Chrome 中对此进行了测试,它适用于我在屏幕上只有一张图像的简单情况;希望我没有在这里写任何错别字。要更改速度,请更改加速度值或更改 setInterval 中的时间。希望这可以帮助!

编辑:是一个有效的 jsFiddle。我不得不使用跨度而不是图像,因为我没有您的确切图像文件,但其他一切都是一样的。


推荐阅读