【WEB基础案例】

轮播图

1.动画
2.没有动画

 // 1. 获取元素  图片  和  h3
const pic = document.querySelector('.pic')
const text = document.querySelector('.text')
// i 记录图片的张数
let i = 0
// 2.开启定时器
setInterval(function () {
    i++
    // 无缝衔接
    if (i >= data.length) {
        i = 0
    }
    // 修改图片的src属性
    // console.log(data[i].imgSrc)
    pic.src = data[i].imgSrc
    // 修改文字内容
    text.innerHTML = data[i].title
}, 1000)

完整代码来自黑马程序员教程

  <div class="slider">
    <div class="slider-wrapper">
      <img src="./images/slider01.jpg" alt="" />
    </div>
    <div class="slider-footer">
      <p>对人类来说会不会太超前了?</p>
      <ul class="slider-indicator">
        <li class="active"></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
      </ul>
      <div class="toggle">
        <button class="prev">&lt;</button>
        <button class="next">&gt;</button>
      </div>
    </div>
  </div>
  <script>
    // 1. 初始数据
    const data = [
      { url: './images/slider01.jpg', title: '对人类来说会不会太超前了?', color: 'rgb(100, 67, 68)' },
      { url: './images/slider02.jpg', title: '开启剑与雪的黑暗传说!', color: 'rgb(43, 35, 26)' },
      { url: './images/slider03.jpg', title: '真正的jo厨出现了!', color: 'rgb(36, 31, 33)' },
      { url: './images/slider04.jpg', title: '李玉刚:让世界通过B站看到东方大国文化', color: 'rgb(139, 98, 66)' },
      { url: './images/slider05.jpg', title: '快来分享你的寒假日常吧~', color: 'rgb(67, 90, 92)' },
      { url: './images/slider06.jpg', title: '哔哩哔哩小年YEAH', color: 'rgb(166, 131, 143)' },
      { url: './images/slider07.jpg', title: '一站式解决你的电脑配置问题!!!', color: 'rgb(53, 29, 25)' },
      { url: './images/slider08.jpg', title: '谁不想和小猫咪贴贴呢!', color: 'rgb(99, 72, 114)' },
    ]
    // 获取元素
    const img = document.querySelector('.slider-wrapper img')
    const p = document.querySelector('.slider-footer p')
    const footer = document.querySelector('.slider-footer')
    // 1. 右按钮业务
    // 1.1 获取右侧按钮 
    const next = document.querySelector('.next')
    let i = 0  // 信号量 控制播放图片张数
    // 1.2 注册点击事件

    next.addEventListener('click', function () {
      // console.log(11)
      i++
      // 1.6判断条件  如果大于8 就复原为 0
      // if (i >= 8) {
      //   i = 0
      // }
      i = i >= data.length ? 0 : i
      // 1.3 得到对应的对象
      // console.log(data[i])
      // 调用函数
      toggle()
    })
    // 2. 左侧按钮业务
    // 2.1 获取左侧按钮 
    const prev = document.querySelector('.prev')
    // 1.2 注册点击事件
    prev.addEventListener('click', function () {
      i--
      // 判断条件  如果小于0  则爬到最后一张图片索引号是 7
      // if (i < 0) {
      //   i = 7
      // }
      i = i < 0 ? data.length - 1 : i
      // 1.3 得到对应的对象
      // console.log(data[i])
      // 调用函数
      toggle()
    })
    // 声明一个渲染的函数作为复用
    function toggle() {
      // 1.4 渲染对应的数据
      img.src = data[i].url
      p.innerHTML = data[i].title
      footer.style.backgroundColor = data[i].color
      // 1.5 更换小圆点    先移除原来的类名, 当前li再添加 这个 类名
      document.querySelector('.slider-indicator .active').classList.remove('active')
      document.querySelector(`.slider-indicator li:nth-child(${i + 1})`).classList.add('active')
    }


    // 3. 自动播放模块
    let timerId = setInterval(function () {
      // 利用js自动调用点击事件  click()  一定加小括号调用函数
      next.click()
    }, 1000)

    // 4. 鼠标经过大盒子,停止定时器
    const slider = document.querySelector('.slider')
    // 注册事件
    slider.addEventListener('mouseenter', function () {
      // 停止定时器
      clearInterval(timerId)
    })

    // 5. 鼠标离开大盒子,开启定时器
    // 注册事件
    slider.addEventListener('mouseleave', function () {
      // 停止定时器
      if (timerId) clearInterval(timerId)
      // 开启定时器
      timerId = setInterval(function () {
        // 利用js自动调用点击事件  click()  一定加小括号调用函数
        next.click()
      }, 1000)
    })

动态填充表格数据

HTML结构

<table cellspacing="0">
      <thead>
          <tr>
              <th>姓名</th>
              <th>科目</th>
              <th>成绩</th>
              <th>操作</th>
          </tr>
      </thead>
      <tbody>
      </tbody>
  </table>

适合维护使用的代码

这里代码的性能还可以优化,思路是将代码存为数组,然后填充。

<script>
      // 数据
      var datas = [
	      { name: '魏璎珞',subject: 'JavaScript',score: 100}, 
	      {name: '弘历',subject: 'JavaScript',score: 98},
	      { name: '傅恒',subject: 'JavaScript',score: 99}, 
	      {name: '明玉',subject: 'JavaScript',score: 88},
	       {name: '大猪蹄子', subject: 'JavaScript',score: 0}
       ];
      //填充目标 
      const tbody = document.querySelector('tbody');
      datas.forEach((item, index) => {
          const tr = document.createElement('tr');
          tbody.appendChild(tr)
          for (key in item) {
              const td = document.createElement('td');
              td.innerHTML = item[key];
              tr.appendChild(td)
          }
          const td = document.createElement('td');
          td.innerHTML = '<a href="javascript:;">删除 </a>';
          tr.appendChild(td);
      })
</script>

不利于维护,或适合结构不变化的

//使用模板字符串填充
const tbody = document.querySelector('tbody');
let str = '';
datas.forEach((item, index) => {
     const { name, subject, score } = item;
      str += `<tr><td>${name}</td><td>${subject}</td><td>${score}</td><td><a href="javascript:">操作</a></td></tr>`
  });
  tbody.innerHTML = str;

checkbox,全选,不选的案例,

HTML部分

<div class="wrap">
    <table>
        <thead>
            <tr>
                <th>
                    <input type="checkbox" id="j_cbAll" />
                </th>
                <th>商品</th>
                <th>价钱</th>
            </tr>
        </thead>
        <tbody id="j_tb">
            <tr>
                <td>
                    <input type="checkbox" />
                </td>
                <td>iPhone8</td>
                <td>8000</td>
            </tr>
            <tr>
                <td>
                    <input type="checkbox" />
                </td>
                <td>iPad Pro</td>
                <td>5000</td>
            </tr>
            <tr>
                <td>
                    <input type="checkbox" />
                </td>
                <td>iPad Air</td>
                <td>2000</td>
            </tr>
            <tr>
                <td>
                    <input type="checkbox" />
                </td>
                <td>Apple Watch</td>
                <td>2000</td>
            </tr>

        </tbody>
    </table>
</div>

JavaScript

<script>
    //获取目标
    const cbAll = document.querySelector('#j_cbAll');
    const itemCheckBox = document.querySelectorAll('#j_tb input[type=checkbox]');

    //中间配件
    let flag = 0;

    //选择全选按钮,所有的都选上
    cbAll.addEventListener('click', (e) => {
        if (e.target.tagName === 'INPUT') {
            itemCheckBox.forEach((item, index) => {
                item.checked = e.target.checked

                //让全选,不全选的时候与单个选择的情况一致,不出现BUG
                if (cbAll.checked) flag = itemCheckBox.length;
                if (!cbAll.checked) flag = 0;
            })
        }
    });

    //单个选择,当所有的都选上,cbAll也选上,缺一个单择全选cbAll不选中
    itemCheckBox.forEach((item, index) => {
        item.addEventListener('click', () => {
            if (flag < itemCheckBox.length && item.checked) flag++;
            if (flag === itemCheckBox.length) cbAll.checked = true;

            if (flag > 0 && item.checked === false) {
                flag--;
                cbAll.checked = false;
            }
        });
    });
</script>

VUE示例

1.给全选checkbox添加v-model
2.查看每个checkbox是否都checked

TAB栏案例

HTML结构

<div class="tab">
<!-- tab导航栏部分-->
<div class="tab-nav">
   <h3>每日特价</h3>
   <ul>
     <li><a class="active" href="javascript:;">精选</a></li>
     <li><a href="javascript:;">美食</a></li>
     <li><a href="javascript:;">百货</a></li>
     <li><a href="javascript:;">个护</a></li>
     <li><a href="javascript:;">预告</a></li>
   </ul>
 </div>
 <!-- tab内容部分-->
 <div class="tab-content">
   <div class="item active"><img src="./images/tab00.png" alt="" /></div>
   <div class="item"><img src="./images/tab01.png" alt="" /></div>
   <div class="item"><img src="./images/tab02.png" alt="" /></div>
   <div class="item"><img src="./images/tab03.png" alt="" /></div>
   <div class="item"><img src="./images/tab04.png" alt="" /></div>
 </div>
</div>

方法1:采用for循环

<script>
const as = document.querySelectorAll('.tab-nav a');

for (let i = 0; i < as.length; i++) {
  as[i].addEventListener('mouseenter', function () {
    document.querySelector('.tab-nav .active').classList.remove('active');
    document.querySelector('.tab-content .active').classList.remove('active');
    this.classList.add('active');
    document.querySelector(`.tab-content .item:nth-child(${i + 1})`).classList.add('active');
  });
}
</script>

方法2:采用forEach

<script>
    const tabnav = document.querySelector('.tab-nav');
    const tabcontent = document.querySelector('.tab-content');
    const items = document.querySelectorAll('.item');
    tabnav.querySelectorAll('a').forEach((item, index) => {
        item.addEventListener('click', (e) => {
            if (e.target.tagName === 'A') {
                tabnav.querySelector('.active').classList.remove('active');
                e.target.classList.add('active')

                tabcontent.querySelector('.active').classList.remove('active')
                items[index].classList.add('active')
            }
        })
    })
</script>

方法3:使用用自定义属性dataset
…….这里省略1万字

给元素添加样式

function addClass(obj,cn){
var reg = new RegExp(‘\b’+ cn + ‘\b’);
if(!reg.test(obj.className)){
obj.className += ’ '+cn;
}
}
obj:元素名称,cn:样式名称。如果当前元素没有cn对应的样式名称,不会重复添加样式

删除元素样式

function removeClass(obj,cn){
var reg = new RegExp(‘\b’+ cn + ‘\b’);
if(reg.test(obj.className)){
obj.className =obj.className.replace(reg,‘’);
}
}

查找元素样式

function hasClass(obj,cn){
var reg = new RegExp(‘\b’+ cn + ‘\b’);
return reg.test(obj.className)
}

三角形写法

.box{
width:100px;
height:100px;
border-width:10px;
border-style:solid;
border-color:transparent;
Border-top-color:orange;
}

两栏代码,左右布局,两列

.left{position:absolute;left:0;top:0;width:300px;height:100%;background-color:green;}
.right{height:100%;margin-left:300px;background-color:orange;}

手风琴下拉菜单

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>过渡效果手风琴菜单</title>
	<style>
		div,ul,li,h3{padding:0;margin:0;}
		ul{list-style: none;background:yellowgreen;}
		li{display:block;width:100%;height:30px;line-height: 30px;padding-left:10px;box-sizing: border-box;}
		h3{display: block;width:100%;height:40px;line-height: 40px;background:skyblue;padding-left:10px;box-sizing: border-box;border-bottom: 2px solid #ddd;}
		.menu{width:200px;height:auto;}
		.item{background:#ddd;width:100%;}
		
		.itemBox{
			width:100%;
			height:0;
			overflow: hidden;
			transition:height 1s;
		}
		.item:hover > .itemBox{
			height:100px;
		}
		
	</style>
</head>

<body>
	<div class="menu">
		<div class="item">
			<h3>新闻资讯</h3>
			<div class="itemBox">
				<ul>
					<li class="item-link">实时新闻</li>
					<li class="item-link">体育新闻</li>
					<li class="item-link">军事新闻</li>
				</ul>
			</div>
		</div>
		<div class="item">
			<h3>旅游路上</h3>
			<div class="itemBox">
				<ul>
					<li class="item-link">实时新闻</li>
					<li class="item-link">体育新闻</li>
					<li class="item-link">军事新闻</li>
				</ul>
			</div>
		</div>
	</div>
	
</body>
</html>

苹果桌面图标

<!DOCTYPE html>
<html lang="zh-cn">
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1.0" />
		
		<title>12</title>
		<style>
			html,body,div,ul,li,a,img{
				padding:0;
				margin:0;
			}
			body{
				height:100%;
				overflow: hidden;
			}
			img{
				border:0;
				outline: none;
			}
			#wrap{
				position: absolute;
				width:100%;
				left:0;
				bottom:0;
				text-align: center;
				 font-size: 0; 
			}
			#wrap > img {
				width:64px;
			}
		</style>
	</head>
	<body>
		<div id="wrap">
			<img src="file:///D|/web/study/1.png" alt="" />
			<img src="file:///D|/web/study/2.png"  alt="" />
			<img src="file:///D|/web/study/3.png" alt="" />
			<img src="file:///D|/web/study/4.png"  alt="" />
			<img src="file:///D|/web/study/5.png" alt="" />
		</div>
	</body>
	<script type="text/javascript">
		window.onload = function(){
			
			var r = 128;
			var imgNodes = document.querySelectorAll('#wrap > img');
			
			document.onmouseover = function(ev){
				
				ev = ev || event;
				
				for(var i = 0; i < imgNodes.length; i ++){
					
					var a = imgNodes[i].getBoundingClientRect().left + imgNodes[i].offsetWidth / 2 - ev.clientX;
					var b = imgNodes[i].getBoundingClientRect().top + imgNodes[i].offsetHeight / 2 - ev.clientY;
					var c = Math.sqrt(a*a+b*b);
					
					if(c >= r) c = r;
					
					imgNodes[i].style.width = r - c * 0.5 + 'px';
				}
			}
		}
		
	</script>
</html>

安卓图标

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
	.content{
		margin:0 auto;
		padding-top: 20px;
		width:500px;
		height:500px;
		background-color:#ccc;
	}
	.and-head {
		position: relative;
		margin:10px auto;
		width: 250px;
		height: 125px;
		background-color: darkgreen;
		border-radius: 125px 125px 0 0;
	}
	.and-head::before {
		position: absolute;
		left: 80px;
		top: 70px;
		background-color: red;
		width: 20px;
		height: 20px;
		content: "";
		border-radius: 10px;
	}
	.and-head::after {
		position: absolute;
		right: 80px;
		top: 70px;
		border-radius: 10px;
		width: 20px;
		height: 20px;
		background-color: red;
		content: "";
	}
	.and-body{
		position: relative;
		margin: 0 auto;
		width:250px;
		height:250px;
		background-color:darkgreen;
		border-radius:0 0 10px 10px;
	}
	.and-body::before{
		position: absolute;
		left:-40px;
		width:30px;
		height:180px;
		border-radius: 8px;
		background-color:darkgreen;
		content: "";
	}
	.and-body::after{
		position: absolute;
		right:-40px;
		width:30px;
		height:180px;
		border-radius: 8px;
		background-color:darkgreen;
		content: "";
	}
	.and-foot{
		position: relative;
		margin:0 auto;
		width:250px;
		height:100px;
	}
	.and-foot::before{
		position: absolute;
		left:80px;
		top:0px;
		content: "";
		width:30px;
		height:90px;
		border-radius: 0 0 10px 10px;
		background-color:darkgreen;
	}
	.and-foot::after{
		position: absolute;
		right:80px;
		top:0px;
		content: "";
		width:30px;
		height:90px;
		border-radius: 0 0 10px 10px;
		background-color:darkgreen;
	}
</style>
</head>

<body>
	<div class="content">
		<div class="and-head"></div>
		<div class="and-body"></div>
		<div class="and-foot"></div>
	</div>

</body>
</html>

滚动条

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>HTML5每日一练meter标签的应用</title>
        <style>
        #W3Cfuns_meter{display:block; margin:0 auto; width:960px; height:30px;}
        </style>
        <script language="javascript" type="text/javascript">
        window.onload = function()
		{
			var obj = document.getElementById("W3Cfuns_meter");
			var i = 0;
			setInterval(function(){if(i == 1000){i=0;}obj.value = i++;}, 1);
		}
        </script>
    </head>
    
    <body>
        <meter id="W3Cfuns_meter" min="0" max="1000" value="50" low="800" high="900" optimum="100">aaaaaaaaaaa</meter>
    </body>
</html>

页面跳转

用java script脚本来跳转


<html>
 <head>

<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
 <title>正在进入西农大网站</title>
 </head>
 <body>
 <form name=loading> 
  <p align=center> <font color="#0066ff" size="2">正在进入,请稍等</font><font color="#0066ff" size="2" face="Arial">...</font>
  <input type=text name=chart size=46 style="font-family:Arial; font-weight:bolder; color:#0066ff; background-color:#fef4d9; padding:0px; border-style:none;"> 

   <input type=text name=percent size=47 style="color:#0066ff; text-align:center; border-width:medium; border-style:none;"> 
  <script>  
var bar=0  
var line="||"  
var amount="||"  
count()  
function count(){  
bar=bar+2  
amount =amount + line  
document.loading.chart.value=amount  
document.loading.percent.value=bar+"%"  
if (bar<99)  
{setTimeout("count()",100);}  
else  
{window.location = http://www.mycodes.net;}  
}</script> 
 </p> 
 </form><p align="center">

测试:html网页自动跳转代码<br/>

你可以在这里写下你想的一切东西!<br />

如:西北农林科技大学是一所985、211院校。<br /><br />

如果您的浏览器不支持跳转,<a style="text-decoration: none" href="http://www.mycodes.net

"><font color="#FF0000">请点这里</font></a>.</p>
 </body>
 </html>

防抖

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="text" value="123" />
    <button name="btn">点击提交</button>
    <script>
      const debounce = (() => {
        let timer = null;
        return (callback, time = 800) => {
          timer && clearTimeout(timer);
          timer = setTimeout(callback, time);
        };
      })();
      // 例子
      let btn = document.querySelector("button");
      let ipt = document.querySelector("input");
      btn.addEventListener("click", () => {
        debounce(() => {
          console.log(ipt.value);
        }, 500);
      });

      // 应用场景:搜索,调整窗口大小resize,登录,发送短信
    </script>
  </body>
</html>

节流

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="text" />
    <script>
      // 减少一段时间内的触发频率,
      const throttle = (() => {
        let last = 0;
        return (callback, time = 800) => {
          let now = +new Date();
          if (now - last > time) {
            callback();
            last = now;
          }
        };
      })();

      let ipt = document.querySelector("input");
      ipt.addEventListener("input", () => {
        throttle(() => {
          console.log(ipt.value);
        }, 2000);
      });
    </script>
  </body>
</html>

时间相关

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值