2025年3月26日 星期三 甲辰(龙)年 月廿五 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > JavaScript

原生JS项目练习——tab选项卡功能

时间:03-09来源:作者:点击数:32

一、主要功能介绍:

1、写UI结构

2、获取元素

3、for循环遍历数组,给每一个li添加一个index属性并赋值。(原因等会会总结)

4、绑定鼠标的mousemove事件,鼠标移到某个模块,将该模块变色,换上相应的图片

5、当鼠标离开li的时候,就让当前li的背景颜色改变为原来的颜色,图片隐藏

6、鼠标离开ul的时候,将li模块和图片恢复到刚开始的样子

7、主要实现tab栏的来回切换操作

原生JS好,前端学的才是真的好,对以后的发展有很大的作用

二、详细步骤解析:

HTML和CSS代码:

简单写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>

JS代码:

主要步骤:

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>
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门