2012-08-26 272 views

回答

4

在你的情況,原因動畫並不複雜,我的想法是一個頁面(動畫,而不是)上放置兩個圖像。並顯示/隱藏它們在鼠標上/下。

<div id="img_wrap" class="static"> 
    <img id="animated" src="animated.gif" alt=""> 
    <img id="static" src="static.jpg" alt=""> 
</div> 

腳本:

$(function(){ 
    $('#img_wrap').on('mouseenter', function() { 
     $(this).toggleClass('animated', 'static'); 
    }) 
}) 

CSS:

.animated #static, .statiC#animated { 
    display: none; 
} 
.animated #animated, .statiC#static { 
    display: inline; 
} 

或者,你甚至可以用一個簡單的CSS做到這一點,如果你不需要對IE6支持,至極不觸發hover事件,但<a>

CSS:

#img_wrap #static, #img_wrap:hover #animated { 
    display: inline; 
} 
#img_wrap #animated, #img_wrap:hover #static { 
    display: none; 
} 
+0

感謝這.. :) –

+0

非常優雅的解決方案。由OP提供的動畫不會永遠重複。如果它是一個無限的動畫,那麼它會一直重複這種方法。這讓我想到了其他方法! – IcyFlame

+0

該解決方案在FF中對我無效。 – Samir

1

你需要在這裏使用jquery嗎?

gif不加載,但是 .div {background:url('。png'); } .div:hover {background:url('.gif'); }

+0

on'hover'它會在第一次迭代後停止--GIF應該無限循環以使其工作 –

+0

感謝這個.. :) –

+0

@Zoltan:'hover'使得帶有無限重複動畫的GIF在第一次迭代? –

1

如果你只是想顯示一個固定的靜態圖像,而不是動畫,那麼就像改變懸停圖像(使用CSS或JS)一樣簡單。

但是,如果您想要在mouseout上實際凍結當前幀上的動畫,那麼唯一的方法就是手動爲圖片製作動畫,例如,與JS:

(function(){ 
    var imgDownload = $('#BtnDownload'), interval = 250; 

    function startAnimation(img, interval, frameCount) { 
    var src, prefix, ext, toId; 
    if (frameCount) img.data('frames', frameCount); 
    interval = interval || img.data('interval'); 
    src = img.attr('src').split('.'); 
    ext = src.pop(); 
    prefix = src.join('.'); 
    img.data('ext') || img.data('ext', ext); 
    img.data('prefix') || img.data('prefix', prefix); 
    restartAnimation(img, interval); 
    img.hover(function() { 
     restartAnimation(img, interval); 
    }); 
    img.mouseout(function() { 
     clearTimeout($(this).data('timeout-id')); 
    }); 
    } 
    function restartAnimation(img, interval) { 
    todId = setTimeout(animate, interval, img); 
    img.data('timeout-id', toId); 
    } 
    function animate(img) { 
    var currentFrame, nextFrame, frameCount, prefix, ext; 
    currentFrame = img.data('current-frame'); 
    frameCount = img.data('frames'); 
    prefix = img.data('prefix'); 
    ext = img.data('ext'); 

    nextFrame = currentFrame + 1; 
    if (nextFrame >= frameCount) nextFrame = 0; 
    img.data('current-frame', nextFrame); 
    img.attr('src', prefix + (nextFrame? nextFrame : '') + '.' + ext); 
    } 

    startAnimation(imgDownload, interval); 
)()); 

和下面的HTML:

<img src="/img/btn_download.png" alt="Download" data-frames="6"> 

而且這些影像:

/img/btn_download.png 
/img/btn_download1.png 
/img/btn_download2.png 
/img/btn_download3.png 
/img/btn_download4.png 
/img/btn_download5.png 

注: 這是一個天真的實現。對於產品代碼,您需要預先加載圖像或僅使用spritemaps。但基本概念與手動設置圖像/按鈕的動畫效果相同,因此當您凍結動畫時,它會凍結當前幀。另一種方法是使用類似jsgif,它使用XHR下載GIF文件,解析二進制數據以提取各個幀,然後使用HTML5畫布呈現它們。

0

不,你不能控制圖像的動畫。

你需要兩個版本的每個iamge,一個是動畫的,另一個不是。在懸停時,您可以輕鬆地從一個圖像更改爲另一個圖像。