2017-04-26 86 views
0

現在,我有以下JQuery .animate命令,它將線條圖像從top:0px移動到top:200px使用JQuery .animate將元素上下無限移動

$("#scanner").animate({ top: '200px' }, 2000); 

我怎樣才能從動畫回200px0px等就行了形象,200px,repetativly,infinitly? (爲了澄清,動畫就像條形碼掃描儀)。

+1

改用css,爲什麼腳本? – skobaljic

+0

@skobaljic這是整個腳本的一部分。動畫將使用變量,所以它必須是一個腳本。 –

回答

2

設置爲成功回調

function topInc(){ 
    $("#scanner").animate({ top: '200px' }, 2000, topDec); 
} 

function topDec(){ 
    $("#scanner").animate({ top: '0' }, 2000, topInc); 
} 

topInc(); 
1

萬一有人需要它,CSS的解決辦法是:

.scan-box { 
 
    position: relative; 
 
    width: 200px; 
 
    height: 200px; 
 
    border: 1px solid black; 
 
} 
 

 
#scanner { 
 
    position: absolute; 
 
    left: 0; 
 
    top: 0; 
 
    width: 100%; 
 
    height: 10px; 
 
    background: none rgba(255, 0, 0, .5); 
 
    animation: scanning 3s linear infinite; 
 
} 
 

 
@keyframes scanning { 
 
    0% { 
 
     top: 0; 
 
    } 
 
    50% { 
 
     top: calc(100% - 10px); 
 
    } 
 
    100% { 
 
     top: 0; 
 
    } 
 
}
<div class="scan-box"> 
 
    Scanning... 
 
    <div id="scanner"></div> 
 
</div>

作爲獎勵,一些定製可以做到通過其他款式或使用CSS Variables

:root { 
 
    --data-from: 0; 
 
    --data-to: 100%; 
 
} 
 

 
.scan-box { 
 
    position: relative; 
 
    width: 150px; 
 
    height: 150px; 
 
    border: 1px solid black; 
 
    float: left; 
 
    margin: 0 10px 10px 0; 
 
} 
 

 
.scanner { 
 
    position: absolute; 
 
    left: 0; 
 
    top: 0; 
 
    width: 100%; 
 
    height: 10px; 
 
    background: none rgba(255, 0, 0, .5); 
 
    animation: scanning 3s linear infinite; 
 
} 
 

 
.scanner-ease-in-out { 
 
    animation: scanning 3s ease-in-out infinite; 
 
} 
 

 
@keyframes scanning { 
 
    0% { 
 
     top: var(--data-from); 
 
    } 
 
    50% { 
 
     top: calc(var(--data-to) - 10px); 
 
    } 
 
    100% { 
 
     top: var(--data-from); 
 
    } 
 
}
<div class="scan-box"> 
 
    Scanning... 
 
    <div class="scanner"></div> 
 
</div> 
 

 
<div class="scan-box"> 
 
    Scanning... 
 
    <div class="scanner scanner-ease-in-out"></div> 
 
</div> 
 

 
<div class="scan-box"> 
 
    Scanning... 
 
    <div class="scanner" style="--data-from:25%;--data-to:75%"></div> 
 
</div>

同樣在JSFiddle

+0

謝謝你的回答。你很好地闡述了CSS方法。 –