纯css实现开关、轮播

html 董德咏
文章标签: html css

GIF 2020-8-14 20-59-44.gif

css样式:

	/* 基本样式 */
			* {
				margin: 0px;
				padding: 0px;
			}

			ul,
			li {
				list-style: none;
			}

			img {
				width: 100%;
				display: block;
			}

			input {
				display: none;
			}

			label {
				display: inline-block;
				width: 10px;
				height: 10px;
				border: #fff 3px solid;
			}

			#main {
				margin:10% auto;
				width: 700px;
				height: 380px;
				overflow: hidden;
				position: relative;
			}

			#btn {
				position: absolute;
				bottom: 15px;
				z-index: 5;
				left: 50%;
				transform: translateX(-50%);
				cursor: pointer;
			}

			ul {
				width: 2800px;
				position: absolute;
				z-index: 1;
				transition: 1s
			}

			li {
				float: left;
				width: 700px;
			}

			/* 实现点击轮播 */
			/* 按钮变色 */
			input#one:checked~#btn label:first-child {
				background-color: #000000;
			}

			input#two:checked~#btn label:nth-child(2) {
				background-color: #000000;
			}

			input#three:checked~#btn label:nth-child(3) {
				background-color: #000000;
			}

			input#four:checked~#btn label:nth-child(4) {
				background-color: #000000;
			}

			/* 换图 */
			input#one:checked~ul {
				left: 0%;
			}

			input#two:checked~ul {
				left: -100%;
			}

			input#three:checked~ul {
				left: -200%;
			}

			input#four:checked~ul {
				left: -300%;
			}

html:

<div id="main">
			<input type="radio" name="pic" id="one" checked="checked"/>
			<input type="radio" name="pic" id="two" />
			<input type="radio" name="pic" id="three" />
			<input type="radio" name="pic" id="four" />
			<!-- 这里加一个div包裹label就是为了方便放置label -->
			<div id="btn">
				<label for="one"></label>
				<label for="two"></label>
				<label for="three"></label>
				<label for="four"></label>
			</div>
			<!-- ul就是轮播里层父元素了 -->
			<ul>
				<li><img src="imgs/1.jpg"></li>
				<li><img src="imgs/2.jpg"></li>
				<li><img src="imgs/3.jpg"></li>
				<li><img src="imgs/4.jpg"></li>
			</ul>
		</div>

实现思路:

核心:“:checked 选择器匹配每个已被选中的 input 元素(只用于单选按钮和复选框)。”

然后input绑定label for联动,input放在外层父元素里面最上面,就是为了能通过css选择器选中ul标签,然后通过点击label实现单选框的选中状态,

然后用:checked来选择ul的左偏移实现轮播效果,当然,给ul标签加点过渡时间就有过渡动画了。

参考地址:梁志芳---利用CSS中input制作开关、轮播图


还能输出{{restrictNumber}}个字符  
  • {{reply.author}}

    {{CommonUtil.formateDate(reply.ac_CommentDate).shortTime}}
  • 回复了{{Comments.author}} :