What I'd like to do is animate a small image as well as a div (or an image within a div) from the right to the left of the screen, repeating once the image/div leaves the screen.
I found an example online that moves an image/div from left to right, but not all the way to the other side of the screen, and I am struggling to make it from right to left.
Here's what I have been doing
function moveTruck() {
$("#ImageToMove").animate({
"margin-right": "5000px"
}, 3000, function () { $("#ImageToMove").css("margin-right", "10000"); moveTruck(); });
}
moveTruck();
Playing with the margin-right values. My CSS class is:
.HomeImageAnimate{
position:absolute;
margin-top:80px;
right:1000px;
}
Try setting , animating left
property using values of window.innerWidth
, container element width
(function fx(el) { $(el).css("left", window.innerWidth) .animate({ left: "-" + (window.innerWidth - $(el).width() * 2) }, 3000, "linear", function() { fx(this) }) }($("div")))
body { overflow: hidden; } div { width: 50px; height: 50px; position: absolute; } img { background: gold; width: 50px; height: 50px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <div> <img /> </div>
Try this out, this truck div repeatedly goes from right to left.
HTML:
<div class="truck"></div>
CSS:
body{
background: green;
overflow: hidden;
}
.truck {
margin-top:20px;
width: 272px;
height: 174px;
cursor:pointer;
position: absolute;
margin-right: -150px;
z-index: 3;
background: red;
border-radius:4px;
width:200px;
height:50px;
}
JS:
$(function() {
var moveTruck = function(){
$(".truck").delay(2000).animate( {'right': '120%' }, 5000,'linear',function(){
$(this).css({'right': '-50px'});
moveTruck();
});
}
moveTruck();
})
function move(){
width = $(window).width(); objectWidth = $('#demo').width(); margin = width + objectWidth + 'px'; restart = -100 - objectWidth + 'px'; $('#demo').animate({ 'margin-left': margin }, 3000, function(){ $('#demo').css('margin-left', restart); move(); }); }
move();
Try this out, it calculates the exact width of object and window - should always work no matter the screen size. You were trying to use an absolute pixel value, won't always work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.