web API day6

102 阅读6分钟

加载事件

load 事件

  • 加载外部资源(如图片、外联CSS和JavaScript等)加载完毕时触发的事件。

  • 为什么要学? 有些时候需要等页面资源全部处理完了做一些事情。 老代码喜欢把 script 写在 head 中,这时候直接找 dom 元素找不到。

  • 事件名:load

  • 监听页面所有资源加载完毕: 给 window 添加 load 事件。

        <script>
            window.addEventListener("load",function(){
                //执行的操作
                console.log(标签元素和标签内容都加载完毕-就出现)
            })
        </script>
    

    注意:不光可以监听整个页面资源加载完毕,也可以针对某个资源绑定load事件。

作用

获取元素的内容时,直接获取,可能元素还没加载出来,那获取出来的数据是不对的,所以放在load事件里,能保证等待里面元素都加载好了,再获取。

<body>
    <h1></h1>
    <img src="../day5/img/微信图片_20220411164226.png" alt="">
    <script>
        
        const img=document.querySelector("img")
        const h1=document.querySelector("h1")

        //直接获取图片的高度
        //console.log(img.height); //会显示0,因为代码执行到这里的时候,图片内容还没加载出来

        //放在load事件里面,即可等加载完毕内容再获取图片的高度
        window.addEventListener('load',function(){
            console.log(img.height); 
            h1.innerText=img.height;
        })

    </script>
</body>

DOMContentLoaded 事件

  • 当初始的 HTML 文档被完全加载和解析完成之后,DOMContentLoaded 事件被触发,而无需等待样式表、图像等完全加载。
  • 事件名:DOMContentLoaded ;
  • 监听页面DOM加载完毕: 给 document 添加 DOMContentLoaded 事件。

注:

  1. 因为以前写js 习惯写在head标签中,所以js会先执行, dom元素还没有开始加载。
  2. 现在js都是写在上面,所以现在该方法用的比较少。

元素大小和位置

scroll家族

使用场景: 我们想要页面滚动一段距离,比如100px,就让某些元素显示隐藏,那我们怎么知道,页面滚动了100像素呢? 就可以使用scroll 来检测页面滚动的距离。

  • 获取宽高: 获取元素的内容总宽高(不包含滚动条,是整个滚动区域的大小)返回值不带单位 scrollWidthscrollHeight
获取宽高:      scrollWidth/scrollHeight  不包含 滚动条 大小 
               scrollWidth/scrollHeight  等于整个可以滚动的区域大小 

示例:

<script>
        const div = document.querySelector("div")
        //输出div 可以滚动的高度
        console.log(div.scrollHeight) //获取div可以滚动的高度,获取的高度会减掉滚动条的17px
        console.log(div.scrollWidth) //获取div可以滚动的宽度,获取的宽度会减掉滚动条的17px
    </script>
  • 获取位置: 获取元素内容往左、往上滚出去看不到的距离。 scrollLeftscrollTop 这两个属性是可以修改的。
      1 页面滚动 使用  .addEventListener("scroll") 事件
      2 页面垂直的滚动距离 document.documentElement.scrollTop
      3 页面水平的滚动距离 document.documentElement.scrollleft
		
<script>
        const div = document.querySelector("div")

        //获取当前容器滚动了的距离
        div.addEventListener("scroll", function () {
            //console.log(this.scrolltop) //获取当前容器的滚动距离 -垂直方向的
            console.log(this.scrollLeft) //获取当前容器的滚动距离 -水平方向的
        })
    </script>

注意:

  1. 小细节 PC端的滚动条大小 17px。
  2. 小细节 移动端的滚动条 不占大小 。

offset家族

<style>
    *{
        padding: 0;
        margin: 0;
        box-sizing: border-box;
    }
    .one{
        width: 300px;
        height: 300px;
        background-color: pink;

        /* 给第一个盒子加个定位 */
        position: fixed;
        left: 20px;
        top: 30pxs;
        padding: 20px;
    }
    .two{
        width: 200px;
        height: 200px;
        background-color: skyblue;

        /* 给第二个盒子加滚动条 */
        overflow: scroll; 
    }
</style>

<body>
    <div class="one">
        哈哈哈哈哈
        <div class="two"></div>
    </div>

    <script>
        const two = document.querySelector(".two")

        console.log(two.offsetWidth);//获取第二个盒子的宽度,包含滚动条的大小
        console.log(two.offsetHeight);//获取第二个盒子的高度,包含滚动条的大小
    

        //获取当前元素距离 定位了的父元素的大小(找不到定位了的父元素,相对于页面来计算)
        console.log(two.offsetLeft)  //水平方向的距离
        console.log(two.offsetTop)  //垂直方向的记录

         /* 
      总结 offset家族
      1 offsetWidth  获取元素的宽度 包含这滚动条
      2 offsetHeight 获取元素的高度 包含这滚动条
      3 offsetLeft 获取定位了的父元素的 水平距离 左  (往上找定位了的父元素,父亲没有就找爷爷,以此类推)
      4 offsetTop 获取定位了的父元素的 垂直距离 上   (往上找定位了的父元素,父亲没有就找爷爷,以此类推)
       */
    </script>
</body>

client家族

<body>
    <div></div>

    <script>
        const div = document.querySelector("div");

        //获取高度和宽度
        console.log(div.clientHeight); //获取可视区域的高度(不包含滚动条)
        console.log(div.clientWidth); //获取可视区域的宽度(不包含滚动条)

        //获取边框的大小
        console.log(div.clientLeft); // 左边框
       // console.log(div.clientRight); // 获取不了右边框
        console.log(div.clientTop); // 上边框  

    </script>
</body>

区别总结

3种家族的区别总结:

获取高度和宽度
scollWidth /scollHeight获取整个滚动区域的宽度和高度(不包含滚动条的大小)
offsetWidth/offsetHeight获取可视区域的宽度和高度(包含滚动条的大小)
offsetWidth/offsetHeight获取可视区域的宽度和宽度(不包含滚动条的大小)
获取滚动距离
scrollLeft / scrollTop获取水平和垂直方向滚动的距离
offsetLeft /offsetTop获取与定位了的父元素的水平和垂直距离(寻找定位的元素按就近原则寻找,如父元素都没有定位,那就相对页面的距离)
clientLeft / clientTop获取左边框和上边框的大小

屏幕大小改变事件

resize(window) 语法示例:

    <style>
        div {
            width: 1rem;
            height: 1rem;
            font-size: 1rem;
            background-color: pink;
        }
    </style>
</head>

<body>
    <div>111</div>

    <script>
        //页面大小发生变化了 就会触发的事件 resize
        window.addEventListener("resize", function (event) {
            console.log("页面大小变化了")

            //打印 当前页面的宽度
            console.log(document.body.offsetWidth);

            //设置页面html标签的字体大小为屏幕的十分之一
            document.documentElement.style.fontSize = document.body.offsetWidth / 10 + 'px';

        })


        // 之前做响应式布局的时候  发一个js文件  方便根据当前页面的宽度 告诉我们屏幕的种类和宽度,就是根据这个写的
        window.addEventListener("resize", function () {
            const width = document.body.offsetWidth;

            if (width > 1200) {
                document.querySelector('title').innerText = `大屏幕 ${width}`;
            } else if (width > 992) {
                document.querySelector('title').innerText = `中等屏幕 ${width}`;
            } else if (width > 768) {
                document.querySelector('title').innerText = `小屏幕 ${width}`;
            } else {
                document.querySelector('title').innerText = `极小屏幕 ${width}`;
            }
        })
    </script>
</body>

轮播图

    <script>
      let lilist = document.querySelectorAll(".indicator ul li") //获取10个li小图
      let bigImg=document.querySelectorAll(".slides ul li") //获取上面的大图
      let h3 = document.querySelector('h3')

      //循环点击小li时 绑定 点击事件
    for (let index = 0; index < lilist.length; index++) {
       lilist[index].addEventListener("click",function(){
        // for (let i = 0; i < lilist.length; i++) {
        //   循环让所有小li移除active 类名
        //   lilist[i].classList.remove('active');
        //    循环让所有的大图移除active 类名
        //   bigImg[i].classList.remove("active");
        // }

        //上面循环移除的类名可以优化这样写:直接获取到li里的所有active类名的元素,移除掉类名
        document.querySelector(".indicator li.active").classList.remove("active");
        document.querySelector(".slides li.active").classList.remove("active");

        lilist[index].classList.add('active'); //选中的这个单独增加active类名
        bigImg[index].classList.add("active"); //选中的大图加active类名
        h3.innerText=`第${index+1}张图的描述信息`


       });//点击事件的结尾
    };
    </script>

swiper插件

是一个 第三方的插件。

使用swiper完成轮播图:

<!-- 
  1.下载swiper的对应文件  css+js 
  2.分别引入他们
  3.拷贝别人的固定结构
  4.拷贝写给的swiper 初始化js代码
-->
<!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>
    <link rel="stylesheet" href="./swiper/swiper-bundle.min.css">
    <style>
        .swiper {
            width: 1200px;
            height: 500px;
        }

        img {
            width: 100%;
        }
    </style>
</head>

<body>
    <div class="swiper">
        <div class="swiper-wrapper">
            <div class="swiper-slide"><img src="./08-焦点轮播图/assets/b_01(1).jpg" alt=""></div>
            <div class="swiper-slide"><img src="./08-焦点轮播图/assets/b_02(1).jpg" alt=""></div>
            <div class="swiper-slide"><img src="./08-焦点轮播图/assets/b_03(1).jpg" alt=""></div>

        </div>
        <!-- 如果需要分页器 -->
        <div class="swiper-pagination"></div>

        <!-- 如果需要导航按钮 -->
        <div class="swiper-button-prev"></div>
        <div class="swiper-button-next"></div>

        <!-- 如果需要滚动条 -->
        <div class="swiper-scrollbar"></div>
    </div>
    <script src="./swiper/swiper-bundle.min.js"></script>
    <script>
        var mySwiper = new Swiper('.swiper', {
            //direction: 'vertical', // 垂直切换选项
            loop: true, // 循环模式选项

            // 如果需要分页器
            pagination: {
                el: '.swiper-pagination',
            },

            // 如果需要前进后退按钮
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            },

            // 如果需要滚动条
            scrollbar: {
                el: '.swiper-scrollbar',
            },


        })        
    </script>
</body>

</html>

window对象

BOM

  • BOM(Browser Object Model ) 是浏览器对象模型。

1649923502989

  • window 是浏览器内置中的全局对象,我们所学习的所有 Web APIs 的知识内容都是基于 window 对象实现的。
  • window 对象下包含了 navigator、location、document、history、screen 5个属性,即所谓的 BOM (浏览器对象模型)。
  • document 是实现 DOM 的基础,它其实是依附于 window 的属性。
  • 注:依附于 window 对象的所有属性和方法,使用时可以省略 window。

延时器

定时器-延时函数

  • JavaScript 内置的一个用来让代码延迟执行的函数,叫 setTimeout
  • 语法:
setTimeout(回调函数,等待的毫秒数)
  • setTimeout 仅仅只执行一次,所以可以理解为就是把一段代码延迟执行, 平时省略window。
  • 清除延时函数:
let timer = setTimeout(回调函数,等待的毫秒数);
clearTimeout(timer);

示例:

    <script>
        //延时器  setTimeout(function(){},等待的毫秒数)
        setTimeout(function(){
            console.log("只会执行一次")
        },5000)
    </script>

延时器关闭广告示例:

<style>
    div{
        width: 300px;
        height: 300px;
        background-color: pink;
        color: #fff;
        text-align: center;
        line-height: 300px;
    }
</style>

<body>
    <div>我是广告...</div>

    <script>
        //使用延时器 让他5秒后关闭广告
        setTimeout(function(){
            document.querySelector("div").style.display="none";
        },5000)
    </script>
</body>

两种定时器对比:

  • setInterval 的特征是重复执行,首次执行会延时。

  • setTimeout 的特征是延时执行,只执行 1 次。

  • setTimeout 结合递归函数,能模拟 setInterval 重复执行。

  • clearTimeout 清除由 setTimeout 创建的定时任务。

    • 创建的定时器应该由clearInterval来清除。
    • 创建的延迟器应该由clrearTimeout来清除。

递归

递归就是:

1 一个函数调用自己 。

2 使用场景:

​ 有一个函数,可以打印出 一个dom元素的所有祖先元素 。

​ 不可能提前知道 这个a标签有多少个父元素 。

​ 这个函数接收一个参数,= dom 。

​ 如果这个dom元素有父元素,就继续调用自己函数。

示例:

 <body>
    <div>
      <p>
        <span
          ><a href=""> <button></button> </a
        ></span>
      </p>
    </div>    
   <script>
        //一个函数调用自己 就是递归,
      // let index = 0;
      // function func() {
      //   index++;
      //   console.log(index); 这样打印会一直+下去,直到系统奔溃
      //   func();
      // }
      // func();

       
        //一般的使用情景是
      const button = document.querySelector('button');

      getParent(button);
      function getParent(dom) {
        console.log(dom);
          // 如果有父元素 才会继续找下去
        if (dom.parentNode) {
          getParent(dom.parentNode);
        } else { //没有父元素的话就结束了
          console.log('结束啦');
        }
      }
    </script>
     </body>

location对象

  • location 的数据类型是对象,它拆分并保存了 URL 地址的各个组成部分。
  • 常用属性和方法:
  1. href 属性获取完整的 URL 地址,对其赋值时用于地址的跳转;
  2. search 属性获取地址中携带的参数,符号 ?后面部分;
  3. hash 属性获取地址中的啥希值,符号 # 后面部分;
  4. reload 方法用来刷新当前页面,传入参数 true 时表示强制刷新。

使用href属性 语法:

1649927393058

示例:

<body>
    <button>跳转百度</button>

    <script>
        const button = document.querySelector("button")

        button.addEventListener("click",function(){
            //用location.href的方式跳转
            location.href='https://www.baidu.com/'
        })
    </script>
</body>

其他几个属性的示例:

<body>
    <button>按钮</button>

    <script>
        //1.使用a标签 href 属性 可以实现页面跳转
        //2.在js中 也可以直接跳转 location.href来跳转
        //3.location.href也可以实现刷新:location.href=location.href
        //4.location.reload(true); (true)强制刷新
        //5.search 后一个阶段就会用到它了,是获取 url上 ? 后面一串字符 /17-location.html?a=1&b=2
        //6.hash 学习到了 vue阶段就会用的了,是获取#后面一串字符  


        const button = document.querySelector("button")

        //点击按钮
        button.addEventListener("click", function () {
            //用location.href的方式跳转原页面 也有刷新的功能
            //  location.href = location.href;


        //reload 强制刷新
        // location.reload(true);
        //console.log(location.search)
        // console.log(location.hash)
       })


        //用延时器 2秒后自动刷新
        //setTimeout(function () {
                //用location.href的方式跳转原页面 也有刷新的功能
                //location.href = location.href;
           // }, 2000)


    </script>
</body>

自动刷新和按钮刷新

<body>
    <button>跳转百度</button>

    <script>
        const button = document.querySelector("button")

        //点击按钮刷新
        button.addEventListener("click", function () {
            //用location.href的方式跳转原页面 也有刷新的功能
            location.href = location.href;
        })

        //用延时器 2秒后自动刷新
        setTimeout(function () {
                //用location.href的方式跳转原页面 也有刷新的功能
                location.href = location.href;
            }, 2000)
    </script>
</body>

navigator对象

  • navigator的数据类型是对象,该对象下记录了浏览器自身的相关信息。
  • 常用属性和方法:

通过 userAgent 检测浏览器的版本及平台。

navigator.userAgent 可以知道用户当前的系统版本和浏览器版本

<script>     
      // 检测 userAgent(浏览器信息)
        !(function () {
            const userAgent = navigator.userAgent
            // 验证是否为Android或iPhone
            const android = userAgent.match(/(Android);?[\s\/]+([\d.]+)?/)
            const iphone = userAgent.match(/(iPhone\sOS)\s([\d_]+)/)
           // 如果是Android或iPhone,则跳转至移动站点
            if (android || iphone) {
                location.href = 'http://m.itcast.cn'
            }
        })()

</script>

histroy对象

  • history 的数据类型是对象,该对象与浏览器地址栏的操作相对应,如前进、后退、历史记录等。
  • 常用属性和方法:

1649930541587

history 对象一般在实际开发中比较少用,但是会在一些 OA 办公系统中见到。

示例:

<body>
    <a href="http://www.baidu.com">百度</a>
    <button class="forward">前进</button>
    <button class="back">后退</button>

    <script>
        //获取前进和后退按钮
        const forward =document.querySelector(".forward")
        const back =document.querySelector(".back")

        forward.addEventListener("click",function(){
           // history.forward() //前进功能
            history.go(1) //前进2个记录 要前进几个记录写几
        })

        back.addEventListener("click",function(){
           // history.back() //后退功能
            history.go(-2) //后退两个记录 要后退几个写-几
        })
    </script>
</body>