WEB前端学习——第六次作业(banner图片左右切换按钮)

WEB前端学习——第六次作业(banner图片左右切换按钮)


使用小米商城首页的banner作为举例


代码如下:

DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>title>
		<style>
			.container{
				position: relative;
				width: 100%;
				height: 500px;
			}
			.container>img {
				width: 100%;
				height: 500px;
				position: absolute;
			}
			.container>img:not(:first-child){
				display: none;
			}
			.prev{
				background: url(https://i1.mifile.cn/f/i/2014/cn/icon/icon-slides.png) no-repeat -84px 50%;
				position: absolute;
				top: 50%;
				width: 41px;
				height: 69px;
				margin-top: -35px;
				outline: none;
				cursor: pointer;
				z-index: 10;
			}
			.prev:hover{
				background-color: black;
			}
			.next{
				background: url(https://i1.mifile.cn/f/i/2014/cn/icon/icon-slides.png) no-repeat -125px 50%;
				position: absolute;
				top: 50%;
				width: 41px;
				height: 69px;
				margin-top: -35px;
				outline: none;
				cursor: pointer;
				z-index: 10;
				right: 0;
			}
			.next:hover{
				background-color: black;
			}
		style>
		<script>
			window.onload = () =>{
				var img_arr = document.querySelectorAll(".container > img")
				var index = 0
				img_arr[index].style.display = "block";
				var timer = setInterval(change,3000)
				
				function change(){
					img_arr[index].style.display = "none";
					index = ++index % img_arr.length
					img_arr[index].style.display = "block";
				}
				
				var prev = document.getElementsByClassName("prev")
				prev[0].onclick = function (){
					
					img_arr[index].style.display = "none";
					index = index - 1
					if(index < 0){
						index = index + img_arr.length
					}
					img_arr[index].style.display = "block";
				}
				
				var next = document.getElementsByClassName("next")
				next[0].onclick = function (){
					img_arr[index].style.display = "none";
					index = ++index % img_arr.length
					img_arr[index].style.display = "block";
				}
				
				var banner = document.getElementsByClassName("container")[0];
				banner.onmousemove = function (e) {
					clearInterval(timer)
				}
				banner.onmouseout = function (e) {
					timer = setInterval(change,3000)
				}	
			}
		script>
	head>
	<body>
		<div class="container">
			<div class="prev">div>
			<div class="next">div>
			<img src="https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/0d03df40a5e8ef760731a8f4f3f61172.jpg"/>
			<img src="https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/5c3a918217308ba7341952552675eb89.jpg"/>
			<img src="https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/12674202e53fd1e46b1725be488d93f5.jpg"/>
		div>
	body>
html>

效果演示:

WEB前端学习——第六次作业(banner图片左右切换按钮)_第1张图片

你可能感兴趣的:(前端,javascript)