1、写UI结构
2、获取元素
3、for循环遍历数组,给每一个li添加一个index属性并赋值。(原因等会会总结)
4、绑定鼠标的mousemove事件,鼠标移到某个模块,将该模块变色,换上相应的图片
5、当鼠标离开li的时候,就让当前li的背景颜色改变为原来的颜色,图片隐藏
6、鼠标离开ul的时候,将li模块和图片恢复到刚开始的样子
7、主要实现tab栏的来回切换操作
原生JS好,前端学的才是真的好,对以后的发展有很大的作用
简单写html和css的代码,样式如下:
- <style>
- * {
- margin: 0;
- padding: 0;
- }
-
- .main {
- width: 350px;
- margin: 0 auto;
- }
-
- .container {
- padding-top: 10px;
- width: 600px;
- height: 60px;
- font-size: 0;
- }
-
- .container li {
- width: 150px;
- height: 60px;
- display: inline-block;
- text-align: center;
- line-height: 60px;
- background-color: #eee;
- list-style: none;
- font-size: 20px;
- }
-
- .container li:nth-child(1) {
- background-color: orange;
- }
-
- .box {
- margin-top: 40px;
- width: 600px;
- height: 400px;
- background-size: cover;
- }
-
- .box img {
- display: none;
- width: 100%;
- height: 100%;
- }
-
- .box img:nth-child(1) {
- display: block;
- }
- </style>
- </head>
-
- <body>
- <div class="main">
- <ul class="container">
- <li>大橘</li>
- <li>汪汪</li>
- <li>库库</li>
- <li>斑点</li>
- </ul>
- <div class="box">
- <img src="1.jpg" alt="">
- <img src="2.jpg" alt="">
- <img src="3.jpg" alt="">
- <img src="4.jpg" alt="">
- </div>
主要步骤:
1、获取元素
2、for循环遍历数组,给每一个li添加一个index属性并赋值。(原因等会会总结)
3、绑定鼠标的mousemove事件,鼠标移到某个模块,将该模块变色,换上相应的图片
4、当鼠标离开li的时候,就让当前li的背景颜色改变为原来的颜色,图片隐藏
5、鼠标离开ul的时候,将li模块和图片恢复到刚开始的样子
6、主要实现tab栏的来回切换操作
- <script>
- var lis = document.querySelectorAll("ul li");
- var imgs = document.querySelectorAll(".box img");
- var container = document.querySelector(".container");
- let flag = 0;
- // 当鼠标移入某个li的时候,就将该li的背景颜色改变
- for (let i = 0; i < lis.length; i++) {
- // 在进行for循环的时候,给每一个li的index属性赋值
- lis[i].index = i;
- lis[i].onmouseover = function() {
- // for循环,每次都将图片清空
- for (let j = 0; j < imgs.length; j++) {
- imgs[j].style.display = "none";
- }
- this.style.backgroundColor = "orange";
- imgs[this.index].style.display = "block";
- if (this.index == 0) {
- flag = 1
- } else {
- falg = 0
- }
- }
- // 当鼠标离开li的时候,就让当前li的背景颜色改变为原来的颜色,图片隐藏
- lis[i].onmouseout = function() {
- this.style.backgroundColor = "#eee";
- imgs[this.index].style.display = "none"
- }
-
- }
-
- // 当鼠标离开ul的时候,让li的第一个变成orange,图片变成第一张图片
- container.onmouseleave = function() {
- lis[0].style.backgroundColor = "orange"
- imgs[0].style.display = "block"
- flag = 0
- }
- container.onmouseenter = function() {
- if (flag) {
- lis[0].style.backgroundColor = "orange"
- } else {
- lis[0].style.backgroundColor = "#eee";
- }
-
- }
- </script>