
一、需求
在许多网站的合作伙伴一栏,常常会看到一排排无限地循环滚动的logo墙。
不久前,接到一个类似的需求。需求如下:
1、无限循环滚动;
2、鼠标hover后,暂停滚动,鼠标离开后,继续滚动;
3、支持从左往右和从右往左滚动;
4、滚动速度需要可配置。
简单动画,我们先尝试只使用css实现。
二、实现
1、marquee标签
说到无限循环滚动,很久以前marquee标签可以实现类似的功能,它可以无限循环滚动,并且可以控制方向和速度。但是该标签在HTML5中已经被弃用,虽然还可以正常使用,但w3c不再推荐使用该特性。作为一个标签,只需要负责布局,而不应该有行为特性。
了解marquee标签:marquee标签
2、css3动画
说到无限循环滚动我们会想到使用css3动画。
把animation-iteration-count设置为infinite,代表无限循环播放动画。
为了使动画运动平滑,我们把animation-timing-function设置为linear,代表动画匀速运动。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
padding-top: 200px;
}
@keyframes scrolling {
to {
transform: translateX(100vw);
}
}
.wall-item {
height: 90px;
width: 160px;
background-image: linear-gradient(120deg, #d4fc79 0%, #96e6a1 100%);
animation: scrolling 4s linear infinite;
}
</style>
</head>
<body>
<div class="wall-item"></div>
</body>
</html>
我们上面实现了一个元素的滚动,在多个元素的时候,我们只需为每个元素设置不同的动画延迟时间(animation-delay),让每一项错落开来,就可以实现我们想要的效果了。
至于鼠标hover后暂停动画,我们只需在滚动元素hover时把animation-play-state设置为暂停即可。
有了以上思路,我很快就可以写出一个纯css实现logo墙无限循环滚动的效果。
完整示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta