2016-11-09 59 views
0

我目前有一個腳本功能,它需要一個圖像,並創建一個動畫,允許它從屏幕的一側傳遞到另一側。但是我只是想讓動畫通過比我的容器小得多的屏幕尺寸。我如何更改代碼以允許它執行此操作?如何防止圖像動畫穿過我的整個屏幕而不僅僅是我的容器?

功能:

<script> 
     $(function() { 
      var img = $("#bus"), 
        width = img.get(0).width, 
        screenWidth = $(window).width(), 
        duration = 10000; 

      function animateBus() { 
       img.css("left", -width) 
         .animate({ 
          "left": screenWidth 
         }, duration, animateBus); 
      } 

      animateBus(); 
     }); 

    </script> 

這是我的集裝箱也:

div.container { 
      text-align: left; 
      width: 710px; 
      margin: 0 auto; 
      border: 12px solid black; 
      border-radius: 10px; 
     } 
+0

您是否嘗試用'screenWidth = $(「div.container」).width()''更改'screenWidth = $(window).width()'? – RizkiDPrast

+0

當然我沒有工作 – user7048814

回答

1

變化screenWidth = $(window).width(),screenWidth = $("div.container").width(),

1

下面是一個使用CSS3動畫的例子...

$(window).ready(function() { 
 

 
    $('#animate').on('click', function() { 
 
    $('.bus').addClass('animate'); 
 
    }) 
 
})
.container { 
 
    display: block; 
 
    position: relative; 
 
    width: 75%; 
 
    height: 100px; 
 
    border: 1px solid; 
 
} 
 
.bus { 
 
    position: absolute; 
 
    right: calc(100% - 100px); 
 
    width: 100px; 
 
    height: 100px; 
 
} 
 
.animate { 
 
    -webkit-animation: slide 2s forwards; 
 
    -webkit-animation-delay: 3s; 
 
    animation: slide 2s forwards; 
 
    animation-delay: 1s; 
 
} 
 
@-webkit-keyframes slide { 
 
    100% { 
 
    right: 0; 
 
    } 
 
} 
 
@keyframes slide { 
 
    100% { 
 
    right: 0; 
 
    } 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="container"> 
 
    <img class="bus animate" src="http://lorempixel.com/400/200/"> 
 
</div>

+0

但我不想要一個按鈕?我想要它自動執行它? – user7048814

+0

沒問題!我們可以簡單地將類添加到img元素本身,看看更新 – WalksAway

+0

這不工作,我想放置一個圖像沒有文本。即使當我添加一個圖像,它仍然是完整的一面離開屏幕,而不是在容器 – user7048814

相關問題