JavaScript------BOM

BOM

BOM 浏览器对象模型

  • BOM : Browser Object Model 浏览器对象模型
  • window : 一个 网页 就是 一个 窗口 , 一个 window 对象代表一个网页
  • screen : 和浏览器 屏幕相关的一个对象 (了解)
  • navigator : 和 浏览器导航 相关的 对象 (了解)
  • history : 获取浏览器 历史记录 的对象
  • location : 和 浏览器 网址 相关的 对象
  • document : 和 浏览器 相关的 文档对象
  • frames : 和 浏览器 框架 相关的 对象

DOM

DOM : Document Object Model 文档对象模型

window 窗口

  • var 在窗口中修饰的变量是 全局变量,会默认成为 window的属性
    • var在函数中定义的变量,不是全局变量
  • 在 窗口中定义的函数 ,也会自动 成为 window 的方法
  • 在使用 window 对象的时候,也可以 省略 window 关键字
对话框

对话框 : 会阻塞程序的运行

  • a) 提示框 alert
  • b) 确认框 confirm
  • c) 输入框 prompt
// 提示框 类型 
alert("我是一个提示框")

// 确认对话框 confirm 有返回值, 返回 true / false 
let x = confirm("您确定要删除该数据吗?") 

//输入对话框, 返回输入的内容,如果点击取消按钮,则返回一个 null
let x = prompt("请输入您的手机号")

open() / close() : 打开/关闭一个窗口
  • open(url,target,features):打开窗口
    • url:窗口的链接
    • target:在哪里打开
    • features:窗口的样式
  • close :关闭窗口
let win = false;

function openWin() {
    win = window.open("https://www.bilibili.com/", "_slef", "width=600px,height=300px")
}

function closeWin() {
    win.close()
}
延迟 setTimeout 清除延续 clearTimeout
  • setTimeout(fn , delay) : 用来设置 延迟加载的代码 fn : 延迟执行的函数 delay: 延迟时间,单位是 毫秒
  • 返回一个 延迟的句柄 ,可以通过 clearTimeout(句柄) 取消延迟动作
//a)
setTimeout(function () {
	console.log("hello")
}, 3000)

function w() {
	console.log("hello")
}

//b)
setTimeout(w, 3000)

//c)
setTimeout("w()", 3000)

//d)
setTimeout(function () {
	w()
}, 3000)


<a onclick="closelog()">取消延迟</a>
//递归的输出 hello
function log(n) {
    console.log("hello" + ++n);
    setTimeout(`log(${n})`, 3000);
}

log(0);
轮询 setInterval
  • setInterval(fn, delay) : 用来进行 轮询 (每间隔一段时间、触发代码执行)
  • 可以通过 clearInterval(句柄) 取消轮询动作
function log() {
    console.log("hello")
}

setInterval(log, 3000)
log()
页面倒计时
<script>
    // 获取 div元素
    let div = document.querySelector("#app") ;
    
    // 使用轮询 ,每间隔 1秒修改数据
    let playing = setInterval(function(){
        // 获取 div 标签体中的内容 
        let num = div.innerText - 1 ;
        
        // 将 修改 后的内容,设置到标签中
         div.innerText = num ;
         
         // 当 num 的值 为 0 时候,停止轮询 
         if (num <= 0) {
             clearInterval(playing); 
             // 将内容修改为 过年了!!!
             div.innerText = "过年了" ;
             // 设置字体大小为 80px 
             div.style.fontSize = "120px"; 
         }
    },  1000)
</script>

网址 的组成部分

a) http:// protocal 协议

  • 是计算机在网络中进行数据传输的一种规范

  • 网页主要采用 http 和 https 协议

    • http 和 https 底层采用的 是 TCP/IP 协议
    • http 和 https 应用层协议
    • TCP/IP 是 传输层 协议
    • 浏览器 遵循 http 和 https 协议
  • http 协议采用 明文进行数据传输

  • https 协议 是一种 安全协议、对传输的数据进行加密处理,可以通过证书进行验签

b) 域名 host

  • 是网络中一台计算机的唯一标识,可以简单理解为和IP一一对应
  • 例如 : www.baidu.com
  • 协议和域名之间用 😕/ 分割

c) 端口号 port

  • 用来查找匹配计算机指定的服务
  • 端口号的取值范围是 0 ~ 65535 之间
  • http协议 在进行数据传输的时候,默认采用的端口号是 80
  • https协议采用的默认端口号是 443
  • 域名 和 端口号 之间 使用 : 分割

d) /s 请求路径 path

  • 用来定位 服务中的某一个具体的服务
  • 端口和请求路径使用“/”分割

e) wd=图片 请求参数 parameter

  • 在使用某一个具体的服务的时候传递的数据
  • 请求参数 采用 键=值 的方式进行传递 ,多个参数采用 & 进行分割
  • 请求路径 path 和 请求参数 parameter 之间 用 ? 分割

location 用来操作浏览器的网址

protocol : 获取协议 , 会包含一个 :

  • hostname : 获取IP或者域名
  • host : 获取主机(包含端口)
  • port : 获取端口号
  • pathname : 获取 请求路径
  • search : 获取 请求参数 , 会包含 一个 ?
  • href : 获取网址 ,如果使用赋值语句,可以跳转页面,等价于 assgin
  • hash : 获取锚点
  • assgin(url) : 跳转到指定的网页, 会将记录写入 history 中
  • replace(url) : 跳转到指定的网页, 不会将记录写到 history 中
  • reload() : 刷新页面
// 获取当前网址
let url  = location.href  ; 

// 获取 协议 , 会包含 :
let protocol = location.protocol ; 

// 获取域名 
let domain = location.hostname ;

// 获取 域名和端口
let ipAndPort = location.host ;

// 获取端口号 
let port = location.port ;

// 获取 请求地址 
let path = location.pathname

// 获取 查询请求参数 , 会包含 ?
let search = location.search ;

location 实现页面跳转

  • 实现页面的跳转
    • href和assign进行跳转,会有历史记录
      • location.assign(“https://www/baidu.com”):
      • location.href(url)
    • replace直接替换当前网址,不会在历史中留下访问记录
      • location.replace(url):
  • 刷新页面
    • location.reload()
// location 常见的方法 (可以实现页面跳转,等价于 location.href)
// href 和 assign 进行跳转的时候,会有历史记录 
location.assign("https://www.baidu.com/") 
location.href = "https://www.baidu.com/"

//replace 直接替换当前 网址 ,不会在历史中留下访问记录
location.replace("https://www.baidu.com/")

URL

获取任意网址的每一部分, 使用 URL这个类

  • let url = new URL(“http://www.baidu.com/s?wd=图片”)
  • 获取网址每一部分的属性可以参考 location

URLSearchParams

获取 网址中的 请求参数

  • new URLSearchParams(search) :
  • search : 传入的 是 location.search的部分

URLSearchParams 对象常用的方法

  • get(key) : 根据键 获取值
  • getAll(key) : 根据键 获取多个值
  • has(key) : 判断某个键是否存在

history

  • history.go(n) 前进你n 或者后退n 个网页
  • history.forward() 前进 , 等价于 history.go(1)
  • history.back(); 后退,等价于 history.go(-1)

document

操作 DOM 的步骤

    1. 找到需要操作的 DOM 元素 (需要使用选择器)
    1. 根据元素的 属性 / 方法 来完成具体的效果

选择器 : 为了快速选中 网页中的 标签

常见的选择器

  • a) document.getElementById(“id”) : 根据ID选中对应的元素
    • 根据id选中对应的数据
    • 如果id重复,只选中第一个元素对象
  • b) document.getElementsByTagName(tag) : 根据 标签名 选择 元素
  • c) document.getElementsByName(name) : 根据标签的 name 属性名选择元素
  • d) document.getElementsByClassName(class): 根据标签的 class属性值选择元素

除 getElementById 之外的其他三个方法,均返回一个形似数组的对象

  • e) querySelector( css选择器 ) : 根据css选择器返回满足条件的第一个元素
  • f) querySelectorAll( css选择器) : 根据css选择器返回满足条件的所有元素
<p id="p1">1</p>
<p class="p2"><a>百度</a></p>
<p name="p3">3</p>
<a>新浪</a>

// 根据 id 等于 p1 选中 元素 
let tag = document.getElementById("p1") ;
console.log(tag); 

// 选中  class=p2 的 元素, 返回一个形似数组的对象
let tag1 = document.getElementsByClassName("p2");
console.log(tag1);

// 选中所有的 p 标签 
let tag2 = document.getElementsByTagName("p") ;
console.log(tag2);

// 选中 name属性 等于 p3 的 所有元素 
let tag3 = document.getElementsByName("p3") ;
console.log(tag3);

// 选中 id =p1 的元素 
let p1 = document.querySelector(".p2")
// console.log(p1)
// 获取 p1 元素下的 a 标签 
let a  = p1.querySelector("a")
console.log(a)

dom元素常见的属性

所有的 html 标签 都可以使用

  • id , class , style, title

可以直接通过 元素 调用的属性有

  • id, name , style, title, src , href , value , checked , selected

给元素 class 赋值 只能用 tag.className = “CSS” (只能替换样式)

tag.classList.add(“CSS”) (添加样式)

tag.classList.remove(“CSS”) (删除样式)

dataset 属性

指的是以 data- 开头的属性 , - 后面的值需要满足标识符命名规范

  • <>.dataset.val 获取 dataset 属性
<a id="link" data-url="https://www.iqiyi.com/" data-name="爱奇艺" href="https://www.bilibili.com/">blbl</a>
  <script>
      // 将 百度 超链接 更改为 新浪 
      let tag = document.querySelector("#link"); 
      
      // 获取 dataset 属性 
      let url = tag.dataset.url ; 
      let title = tag.dataset.name ;
      
      // 修改 a 标签的 href 
      tag.href = url ; 
      
      // 修改 标签体 里面的内容 
      tag.innerText = title ;
      
  </script>

dataset 属性 应用

图片 过大, 加载缓慢 常见的解决方案:

  1. 主界面展示多图的时候,采用缩略图 (网站需要存储缩略图 和 原图、需要对图像进行处理)
  2. 图片的延迟加载
  3. 默认图片 + 延迟加载
<div class="images" onscroll="lazyLoadImg(this)">
	<img src="./images/default.png" data-src="images/0001.webp" />
	······			
</div>

<script>
			
    // 获取 所有的图片 
    let imgs = document.querySelectorAll("img");
    // 定义 一个函数 lazyLoadImg ,负责 加载 图片
    function lazyLoadImg(tag) {
        // 获取 图片 距离 父容器的 顶部距离, 如果距离 超出了 父容器的高度,说明该元素还在隐藏状态
        for(let i = 0 ; i < imgs.length ; i++) {
            // 获取 图片对象
            let img = imgs[i] ;
            // 获取 img 元素 距离 父元素 顶部的距离
            
            let tlen =img.offsetTop - tag.scrollTop;
            // 如果 tlen + 图片自身的高度 < 父容器的高度,那么就需要将 真图显示出来 

            
            // 刚刚出现在可见区域,就换真图
            if (tlen  < tag.clientHeight && img.dataset.over != 1) {
                // 获取 img 的 真实地址
                let src = img.dataset.src ;
                img.src = src ;
                img.dataset.over = "1"
            }
        }
    }
    // 进入页面尝试 进行懒加载图片
    window.onload = function() {
        lazyLoadImg(document.querySelector(".images"))
    }
    
</script>

css 到父类的距离

  • offsetLeft : 距离 父元素(最近定位的父元素)的左侧位置 (包含 滚动隐去的距离)

  • offsetTop : 距离 父元素(最近定位的父元素)的顶部位置 (包含 滚动隐去的距离)

  • offsetWidth : 自身的宽度 (包含边框)

  • offsetHeight: 自身的高度 (包含边框)

  • clientLeft : 元素左边框的 宽度

  • clientTop : 元素 上边框的 宽度

  • clientWidth : 自身的宽度 (不包含边框)

  • clientHeight : 自身的高度 (不包含边框)

  • scrollLeft : 滚动条左侧 卷去的 宽度

  • scrollTop : 滚动条顶部 卷去的 高度

  • scrollWidth : 元素的 滚动宽度

  • scrollHeight: 元素的 滚动高度

获取任意元素距离浏览器的位置

/**
 * 获取任意元素距离浏览器的位置
 */
function getPosition(obj) {
    // 获取 到 父元素的 左侧距离
    let lf = obj.offsetLeft ;
    let tp = obj.offsetTop ;

    // 获取 父元素
    let parent = obj.offsetParent ;

    if (parent == null) {
        return { left: lf , top: tp  };
    }
    // 如果 有 父元素
    let {left, top} = getPosition(parent) ;

    return {
        left: left + parent.clientLeft + lf,
        top: top + parent.clientTop + tp
    }
}

/**
 * 支持任意 js dom 对象调用
 */
Element.prototype.getClientPos = function() {
    return getPosition(this);
}

鼠标跟随效果

  • 鼠标 跟随:需要用到的事件是 鼠标移动 mousemove 事件
    • 给 document文档对象绑定事件
    • js 通过 addEventListener 绑定事件
    • 事件名 是 去掉 on
    • event : 事件对象
<script>
    document.addEventListener("mousemove", function(event) {
       // pageX 鼠标在 x轴的坐标,相对于浏览器 , pageY鼠标在 Y轴的坐标,相对于浏览器
       
        // 获取鼠标所在的位置 
        let x = event.pageX ;
        let y = event.pageY ;
        
        //console.log(x, y);
        
        // 创建一个 div.mouse 圆 并设设置 定位方式为 绝对定位 
        // 大小要求 2px - 10px 随机, 颜色随机
        let div = document.createElement("div") ;
        div.className = "mouse" ;
        div.style.position = "absolute" ;
        
        let wh = Math.floor(Math.random() * 15 + 5)
        
        div.style.width = wh + "px" ;
        div.style.height = wh + "px" ;
        div.style.borderRadius = "50%" ;
        div.style.backgroundColor = randomColor();
        
        div.style.left = x - wh /2 + "px" ;
        div.style.top = y - wh/2 + "px" ; 
        
        // 将 div 追加到 body标签中 
        document.body.appendChild(div);
        
        // 100 毫秒后自动删除 div 
        setTimeout(function() {
            div.remove();  // 删除元素
        } , 200)
       
    })
    function randomColor() {
        // 随机产生 0 ~ 255 之间的任意整数 
        let red = Math.floor(Math.random() * 256) ;
        let green = Math.floor(Math.random() * 256) ;
        let blue = Math.floor(Math.random() * 256) ;
        return `rgb(${red}, ${green}, ${blue})` ;
    }
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值