css3 实现无缝滚动

2,978 阅读2分钟
原文链接: zhuanlan.zhihu.com
话不多说,先展示效果:css3无缝滚动

具体代码实现:




	
	标题
	
	
	
		*{padding: 0;margin: 0;}
		.out{
			width: 900px;
			height: 300px;
			margin: 20px auto;
			overflow: hidden;
			text-align: center;
		}
		.con{
			width: 3300px;
			height: 300px;
			overflow: hidden;
			animation: move 8s linear infinite normal;
			animation-fill-mode:forwards;
		}
		.con:hover{
			animation-play-state:paused;
			-webkit-animation-play-state:paused;
		}
		.con li{
			float: left;
			list-style: none;
			overflow: hidden;
		}
		.con img{
			float: left;
			width: 300px;
			height: 300px;
		}

		.pause{
			position: relative;
			height: 60px;
			display: inline-block;
			margin: 20px auto;
			text-align: center;
		}
		.pause:before{
			position: absolute;
			content: "暂停";
			display: inline-block;
			width: 100px;
			height: 60px;
			left: 0px;
			line-height: 60px;
			font-size: 20px;
			color: #fff;
			margin: 0 20px;
			background: orange;
			border: none;
			border-radius: 20px;
			outline: none;
		}

		@keyframes move{
			0%{transform:translateX(0px);}
			100%{transform:translateX(-2400px);}
		}
		.out input{
			display: none;
		}
		.out input:checked ~ .con{
			animation-play-state:paused;
			-webkit-animation-play-state:paused;
		}
		.out input:checked ~ .pause:before{
			content: "滚动";
		}
	


	

对于小白,可能会摸不着头脑,大神请跳过(估计也没有那个大神会看到),现在具体简介一下实现步骤:

一、结构搭建:

首先我们创建了一个类名为out的容器,用于包括无缝滚动,先跳过input框(这个是重点,后面讲),然后创建一个ul列表,内部li浮动布局,已清除横向间距和保证横向布局,这里的布局要点是:子列表li有多少,父元素ul至少全包括li,也就是不能比所有子元素的宽度总和低;

二、滚动思想:

这里实现的无缝滚动,有两种基本的思想;

第一种:通过父元素的scrollLeft逐渐增加来实现;

第二种:通过css3的translate来实现,这里采用的第二种;

三、滚动动画实现:

主要运用animation动画:

    @keyframes move{
	0%{transform:translateX(0px);}
	100%{transform:translateX(-2400px);}
    }

这里100%的时候移动的距离是你一次性想要展示的所有图片的宽度,并不是ul的宽度;

四、css3模仿点击事件:

主角:input:checkbox;

我们都知道chenckbox有两种状态:选中和未选中;那么我们就可以用选中状态来展示点击的效果变化;

label标签:增加鼠标的可用性;因此我在label中放了一个按钮,然后使label的for指向input;那么当点击按钮的时候,就会选中chenckbox;

在css3中有着强大的选择器;比如input:checked;当chenckbox选中的时候被选择;在比如:e ~ e:当前元素后面的所有同辈元素,现在是不是有点思路了呢?

流程就是:

当点击按钮的时候,触发checkbox的check选择器,同时通过 ~ 选择器选择checkbox 后面的元素,使其改变样式(这里就是动画暂停);

五、关于按钮上的文字变化:

就我目前所掌握的(不用插件的情况下),可以使用伪元素的contenr()方法来动态改变伪元素的文字;

总结:

利用表单元素的自带特性和css选择器巧妙模仿点击事件。