我有这段代码,允许我使用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;
}
答案 0 :(得分:2)
首先创建一个图像数组,以便您可以轻松访问所有图像。每当创建图像时,将其推入数组:
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);
}
要设置图像动画,您需要设置某种动画循环并在setInterval
中调用它:
animate = function(){}
setInterval(animate,5); // choose whatever interval you want. Here, it is called every 5 milliseconds
在动画功能内,我们需要添加逻辑以更改每个图像的位置:
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中的时间。希望这会有所帮助!
编辑:here是有效的jsFiddle。我必须使用跨度而不是图像,因为我没有确切的图像文件,但其他所有内容都相同。