2017-09-11 89 views
0

我試圖創建一個視頻預覽時,用戶懸停的圖像(如youtube)。jQuery視頻幀預覽圖像懸停

這些圖像取自FFmpeg,每100幀獲取一幀,並保存在第一個加載圖像的相同目錄中,例如:20-1.jpg。 當用戶將鼠標在第一圖像上,它應該通過名爲例如其他圖像週期:20-2.jpg20-3.jpg20,4.jpg

HTML

獲取項目的ID從Twig{{result.id}}

<div class="card result-card" onmouseover="updateThumb({{ result.id }})"> 
    <a href="{{ url('vedi_oggetto', {'category': catName,'item': result.id,'title': slug}) }}"> 
     <img class="card-img-top img-fluid" id="imgPreview-{{ result.id }}" src="/uploads/photos/{{ result.id }}-1.jpg" alt="Card image cap"> 
    </a> 
</div> 

JS

function updateThumb(id) { 
    var timer, 
     count = 1, 
     cycle = function(el){ 
      var s = el.attr('src'), 
      root = s.substring(0, s.lastIndexOf('/') + 1); 
      count = (count+1)%5; 
      el.attr('src', root + '2-' + ((count===0) ? '5' : count) + '.jpg'); 
     }; 
     $('#imgPreview-' + id).hover(function(){ 
      var $this = $(this); 
      cycle($this); 
      timer = setInterval(function(){ cycle($this); }, 800); 
     }, function(){ 
      clearInterval(timer); 
     }); 
    } 

問題是,當我將鼠標懸停在第一張圖片上時,它按預期方式工作並循環。但是,當我將鼠標懸停在第二張圖像或其他圖像上時,它會顯示所有圖像的第一個圖像週期,因此它僅適用於一張圖像。

+0

在每個'mouseover'再指定'$(「#imgPreview-」 + id).hover(function(){..})'事件,這是錯誤的伴侶:) – skobaljic

+0

此外,最好使用'mouseenter'和'mouseleave'事件,因爲...你可能會失去圖像懸停...並在替換圖像的'src'屬性之前嘗試預先加載圖像。祝你好運 – skobaljic

+0

夥計們,感謝您的想法,可以在回覆中發佈示例嗎? – andreaem

回答

1

比方說你有ID的20和30兩個圖像,比你可以走這條路:

var cycle = function(el) { 
 
    var s = el.attr('src'); 
 
    var root = s.substring(0, s.lastIndexOf('-') + 1); 
 
    var count = s.substring(s.lastIndexOf('-') + 1).replace('.jpg', ''); 
 
    count = (count*1+1)%5; 
 
    console.log(count); 
 
    console.log('-------'); 
 
    el.attr('src', root + ((count === 0) ? '5' : count) + '.jpg'); 
 
}; 
 
$('body').on('mouseenter', '[id^=imgPreview-]', function(e) { 
 
    var thisImage = $(this); 
 
    var timer; 
 
    cycle(thisImage); 
 
    timer = setInterval(function() { 
 
     cycle(thisImage); 
 
    }, 800); 
 
    thisImage.on('mouseleave', function() { 
 
     clearInterval(timer); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<img id="imgPreview-20" src="/uploads/photos/20-1.jpg" /> 
 
<img id="imgPreview-30" src="/uploads/photos/30-1.jpg" />

同樣在JSFiddle

而且我在評論中提到的所有其他問題,你一直用ID 2生成該行的圖像源:

el.attr('src', root + '2-' + ((count===0) ? '5' : count) + '.jpg'); 
+0

謝謝你,你讓我的一天!現在我明白了爲什麼我只有2 - *。jpg文件,該死! – andreaem