本篇文章将给你们带来一个css3的黑科技:如何仅仅使用css来实现全景图的效果?css
最终效果演示:demohtml
<div class="panorama"></div>
首先定义一些基本的样式和动画css3
.panorama { width: 300px; height: 300px; background-image: url(http://7vilbi.com1.z0.glb.clouddn.com/blog/6608185829213862083.jpg); background-size: auto 100%; cursor: pointer; animation: panorama 10s linear infinite alternate; } @keyframes panorama { to { background-position: 100% 0; } }
background-size: auto 100%;
这段代码的意思是让图片的高等于容器的高,而且水平方向自动,即图片最左边贴着容器左侧。git
执行动画的流程是:周而复始、往复交替、线性而且时间周期是10s。github
到这里为止,当咱们打开该网页后,立马会出现一张图片来回水平滑动的效果。可是这样的话,访客可能会被动画吸引而忽略了真正的内容。
咱们的要求是当鼠标悬浮于图片时才让它动起来,咱们固然能够很简单的实现这个效果。布局
删除以前的animation
,添加如下样式。优化
.panorama:hover, .panorama:focus { animation: panorama 10s linear infinite alternate; }
如今的效果是:鼠标移入图片,图片开始水平来回滑动。动画
虽然效果达到了,可是你会发现,当鼠标移出图片,图片马上回到初始位置。
对于咱们来讲,这有点忽然,如何记录图片当前的位置而且当鼠标移入时继续执行动画呢?url
咱们能够依靠这个属性animation-play-state: paused | running
,它表示动画的两个状态:暂停和运行。code
.panorama { width: 300px; height: 300px; background-image: url(http://7vilbi.com1.z0.glb.clouddn.com/blog/6608185829213862083.jpg); background-size: auto 100%; cursor: pointer; animation: panorama 10s linear infinite alternate; animation-play-state: paused; } .panorama:hover, .panorama:focus { animation-play-state: running; } @keyframes panorama { to { background-position: 100% 0; } }
你也能够在个人博客上阅览本篇文章,你的关注是我最大的写做动力,感谢你的支持。