2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > html 禁止gif自动播放 通过CSS或JS实现gif动态图片的停止与播放

html 禁止gif自动播放 通过CSS或JS实现gif动态图片的停止与播放

时间:2019-05-21 07:42:23

相关推荐

html 禁止gif自动播放 通过CSS或JS实现gif动态图片的停止与播放

到需要可以随时随地停止gif动态图片播放的需求的时候,可以通过下面几种方法实现。

方法一:多img资源控制处理

就是准备2套图片,一个是gif动态图片,还有一个是只有一帧的静止的图片,如jpg图片。然后使用JS来回切换的src值为这两张图片地址,或者通过js实现点击就切换显示两张图片。

这种方法的优点就是兼容性强,所有浏览器都可以实现停止效果。然而这种方法有个局限,就是暂停时候呈现的图片永远是同一张。基本上可以说是停止,而不是暂停。

代码如下:

html

css

.inpic {position:relative;}

.inpic img.gif {display:none;}

jquery

$('.inpic img.jpg').click(function(){

$(this).hide().siblings('.gif').show();

});

$('.inpic img.gif').click(function(){

$(this).hide().siblings('.jpg').show();

});

方法二:CSS3 animation控制

也就是我们看到的gif效果并不是一个真正的gif图片,而是使用CSS3的animation属性控制形成的逐帧动态图片效果,说穿了就是animation控制Sprites图片的background-position值模拟gif效果。

例如,新版twitter的Like的效果,貌似就有使用该技术:

使用CSS3 animation实现类gif效果的好处在于,图片可以无损,且我们可以很轻松地控制图片动画的暂停和播放,使用的是:animation-play-state: paused;这个声明。

代码如下:

HTMl

CSS

.love {

display: block;

width: 100px; height: 100px;

background: url(web_heart_animation.png) 0 0 no-repeat;

background-size: 2900%;

animation: heart-burst steps(28) 0.8s infinite both;

}

.stop {

animation-play-state: paused;

}

@keyframes heart-burst {

0% {

background-position: 0%;

}

100% {

background-position: 100%;

}

}

Javascript

var image = document.getElementById("testImg"),

button = document.getElementById("testBtn");

if (image.classList && image && button) {

button.onclick = function() {

if (this.value == '暂停') {

image.classList.add('stop');

this.value = '播放';

} else {

image.classList.remove('stop');

this.value = '暂停';

}

};

}

不足:IE10+等支持CSS3 animation的浏览器才行。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。