问题
What I want to do is this: I want to generate boxes on the Y or X axis of the page (the bottom and left border) and make them move parallel to each other until they've gone off-screen, where I want to delete them. This is what I've done so far:
Codepen.
function generate(){
var $element = $("<div>", {class: "box"});
//Generate random x and y coordinates
var posy = (Math.random() * ($('body').height() - $element.width())).toFixed();
var posx = (Math.random() * ($('body').width() - $element.height())).toFixed();
//Place the box on the x or y axis
var rand = Math.floor(Math.random()*2);
if(rand==0)
{
posx=0;
}else{
posy=0;
}
$element.css(
{'position':'absolute',
'right':posx+'px',
'bottom':posy+'px'});
$("body").append($element);
//Move box diagonally, all the boxes paths are parallel
TweenLite.to($element, 2, {top:0, right:0, ease:Power2.easeOut});
//Delete boxes offscreen
var $boxes=$(".box");
/*$boxes.each(function(){
if($(this).position().left >1300){
$(this).remove();
}
});*/
}
My issues are: how do I exactly find the right point where to animate the box, in a way to move all the boxes parallel to each other? And also, is there a way without using external plugins to find if an element has gone out of the bounds of the page? Thanks for any answer!
EDIT: Here's a drawing to explain myself better. Sorry for my terrible Paint skills!
Now all the boxes converge to the same top:0
& right:0
point, but I'd like to make them go parallel to each other, and so, each one of them should have a different top/right point to go. I'm guessing my issue would be to calculate it, but how do I do exactly? And also this meddles with the off-screen issue I take.
回答1:
Is this the kind of effect you are trying to create?
JavaScript:
function generate(){
var windowHeight = $(window).height();
var windowWidth = $(window).width();
var $element = $('<div>', {class: 'box'});
var initX = parseInt(Math.random() * windowWidth) - (windowWidth * 0.5);
var destX = parseInt(initX) + $(window).height();
$('body').append($element);
TweenLite.fromTo($element, 2, {x:initX, y:0}, {x:destX, y:-windowHeight, ease:Power2.easeOut, onComplete: onCompleteAnimation, onCompleteParams: [$element]});
}
function onCompleteAnimation($element) {
$element.remove();
}
You will notice that I am not animating top
and left
(or right
) properties with position: absolute;
that you were previously doing. Instead, I am animating x
and y
which are essentially translate(x, y)
values. This makes the animation look smooth: Link.
Hope this helps.
来源:https://stackoverflow.com/questions/31630114/jquery-gsap-moving-multiple-elements-parallel-to-each-other