2015-11-07 101 views
0

我想要做的是從屏幕的右側到左側爲小圖像以及div(或div內的圖像)製作動畫,並在圖像/ div離開屏幕時重複該動畫。如何連續將圖像/ div從右向左移動?

我在網上找到一個例子,它從左到右移動一個圖像/ div,但不是所有的方式到屏幕的另一側,我努力使它從右到左。

這裏就是我一直在做

function moveTruck() { 
     $("#ImageToMove").animate({ 
      "margin-right": "5000px" 
     }, 3000, function() { $("#ImageToMove").css("margin-right", "10000"); moveTruck(); }); 
    } 

    moveTruck(); 

與保證金正確的價值觀播放。我的CSS類是:

.HomeImageAnimate{ 
    position:absolute; 
    margin-top:80px; 
    right:1000px; 
} 
+0

化妝演示[這裏](http://jsfiddle.net/)爲更好地說明你想怎麼辦..因爲我們會要求您提供HTML代碼知道什麼「#ImageToMove」是什麼? ..所以演示更好 –

+0

值得注意的是,使用CSS轉換可以實現同樣的效果([示例](http://jsfiddle.net/anwo9ck3/)),使用CSS動畫更容易實現規範變得規範。 – Thriggle

回答

0

嘗試設置,動畫使用的window.innerWidthleft財產,容器元素的寬度

(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>

0

嘗試了這一點,這輛車DIV反覆從右變向左。

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(); 
}) 

CODEPEN DEMO

0

功能MOV e(){

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();

試試這個,它計算物體和窗口的確切寬度 - 無論屏幕大小如何都應該始終工作。您嘗試使用絕對像素值,並不總是有效。

https://jsfiddle.net/w9pgmm9d/3/