不会点击上方导航换图,求教

来源:6-2 作业题

让我带上思考帽

2018-01-08 17:51:23

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript6-2练习</title>
<link rel="stylesheet" href="css/6-2.css">
</head>
<body>
<div class="banner" id="banner">
<!-- 轮播图菜单 -->
<div class="bannerMenu" id="bannerMenu">
<div class="bgcolor">首页</div>
<div>点击看看</div>
<div>会自动的</div>
<div>我的网站</div>
</div>
<!-- 轮播图  -->
<div class="bannerSlide" id="bannerSlide">
<div><img src="img/1.jpg" alt=""></div>
<div><img src="img/2.jpg" alt=""></div>
<div><img src="img/3.jpg" alt=""></div>
<div><img src="img/4.jpg" alt=""></div>
</div>
</div>
<script src="js/6-2.js"></script>
</body>
</html>
*{
	margin:0;
	padding:0;
}
body{
	font-family:"Microsoft YaHei";
}
.banner {
	width: 800px;
	height: 450px;
	position: relative;
	left: 0;
	right: 0;
	margin: 0 auto;
}
.banner  .bannerMenu{
	width: 796px;
	height: 32px;
	border: dotted 2px rgba(0,0,0,0.2);
	border-bottom: none;
	border-radius: 10px 10px 0 0 ;
	padding: -2px -2px 0 -2px;
}
.banner .bannerMenu div {
	display: inline;
	width: 199px;
	height: 32px;
	float: left;
	line-height: 30px;
	text-align: center;
	border-radius: 10px 10px 0 0 ;
	font-size: 22px;
	cursor: pointer;
}
.banner .bannerSlide{
	width: 800px;
	height: 418px;
}
.banner .bannerSlide img{
	/*display: none;*/
	width: 800px;
	height: 418px;
	/*margin-left: -2px;*/
	position: absolute;
}
.bgcolor{
	background-color: #ffcc00; 
}
function byId(id) {
	return typeof(id) === "string"?document.getElementById(id):id;
}


var index=0;
var timer=null;
var menu=byId('bannerMenu').getElementsByTagName('div');
var img=byId('bannerSlide').getElementsByTagName('div');
var main=byId(banner);
var len=menu.length;
main.onmouseover=function () {
	// 清除定时器
	if(timer) {
		clearInterval(timer);
	}
}
main.onmouseout=function () {
	// 开始定时器
	timer=setInterval(function(){
		index++;
		index=index%len;
		console.log(index);	
		chageImg();
	},1000);
}
function chageImg(){
	for(var i=0;i<len;i++){
		img[i].style.display="none";
		menu[i].className="";
	}
	img[index].style.display="block";
	menu[index].className="bgcolor";
}
main.onmouseout();


写回答

1回答

怎么都被占用了呢

2018-01-08

首先有一处错误,获取banner元素时,要传入ById内字符串,如下图第一处标注进行修改:

http://img.mukewang.com/climg/5a5343160001314108050579.jpg

第二处标注,就是我帮你写的点击导航项切换图片,首先4个导航都可点击切换,所以使用遍历给4个导航绑定单击事件,其次,单击导航项的时候要切换到相应的图片,导航项要和图片有对应的索引,我们点击的时候也要知道它的索引值是几,然后让对应索引的图片显示。所以通过.id的方式给4个导航项添加一个表示着索引值的标志,在单击事件发生时,获取当前导航项的索引值,赋值给控制着轮播的全局变量index,调用changeImg函数即可


1

0 学习 · 36712 问题

查看课程