Home >Web Front-end >JS Tutorial >Organize and summarize common BOM operations in JavaScript

Organize and summarize common BOM operations in JavaScript

WBOY
WBOYforward
2022-06-01 11:43:512557browse

This article brings you relevant knowledge about javascript, which mainly introduces related issues about BOM operations, including common events of window objects, JavaScript execution mechanisms, etc. Let’s take a look at it together, I hope it will be helpful to everyone.

Organize and summarize common BOM operations in JavaScript

[Related recommendations: javascript video tutorial, web front-end

Common events of window objects

  • Window loading event:

    • window.onload: Page loading event, this event will be triggered when the document content is completely loaded (including images, script files, CSS file, etc.) to call the processing function.
    • document.addEventListener('DOMContentLoaded', function(){}): Only when the DOM is loaded, excluding style sheets, pictures, flash, compatibility
  • Events to adjust window size:

    • window.onresize: Adjust window size loading event
  • window.open() method Can be used to navigate to a specified URL, or can be used to open a new browser window

    • This method receives 4 parameters: the URL to be loaded, the target window, the characteristic string and the new window indicating that the new window is browsing Whether to replace the Boolean value of the currently loaded page in the browser history
    • window.open("http://www.wrox.com/", "wroxWindow","height=400,width=400 ,top=10,left=10,resizable=yes");
  • ##Timer:

      setInterval(handler: any , timeout?: long, arguments…: any): Loop call
    • clearInterval(handle?: long): Cancel setInterval
    • setTimeout(handler: any, timeout?: long, arguments…: any): one-time
    • clearTimeout(handle?: long): cancel setTimeout
  • ##window.scroll(x, y)
  • window.scrollTo(x, y): Both are used the same way to change the position of the horizontal and vertical scroll bars, provided that there must be scroll bars on the page
  • window.scrollBy(x, y): The cumulative scrolling of the scroll bar, positive numbers go down, negative numbers go up window.scrollBy(0, 10): When called every 100 milliseconds, the scroll bar moves 10 pixels
  • window.getComputedStyle(elem, pseudo class)
  • Dialog box
  • alert
    • alert( "Prompt string")
      • pops up a warning box and displays the prompt string text in the warning box
      confirm
    • confirm("Prompt character String")
      • Display a confirmation box and display the prompt string in the confirmation box
      • When the user clicks the "Confirm" button, it returns true, and when the user clicks "Cancel", it returns false
      prompt
    • prompt("prompt string", "default value")
      • Display an input box, display the prompt string in the input box, and wait for the user Input
      • Returns user input when the user clicks the "Confirm" button, returns null value when clicking "Cancel"
  • JavaScript execution Mechanism

Run js script, put the js code into the execution stack in a synchronous execution mode, and put the JS asynchronous code (events, timers, ajax, resource loading load, error) encountered during the execution stack into web APIs (Task queue), when the code in the execution stack is completed, go to the task queue to get the first one for execution. After execution, go to the task queue to get the next one for execution, and execute it repeatedly (event loop) until the execution in the task queue Complete

location object

window.history is used to obtain the address URL of the current page and redirect the browser to the new page

http://www.itcast.cn:80/index.html?name=andy&age=1#link
http:通信协议
www.itcast.cn:域名80:端口
index.html:路径?name=andy&age=1:参数
#link 片段:锚点、链接
Organize and summarize common BOM operations in JavaScriptObject properties:

href*: Get or set the entire URL
  • host: Return the host name (domain name)
  • hostname: Set or return the current URL Host name
  • post: Return port number
  • pathname: Return path
  • search*: Return parameter
  • hash: Return fragment (content after # )
  • protocol: Set or return the protocol of the current URL
  • Object method:

assign: Like href, you can jump to the page (also known as For the redirected page)
  • replace: replace the current page, because the history is not recorded, so the page cannot be returned
  • reload: reload the page, equivalent to the refresh function
  • navigator object

Organize and summarize common BOM operations in JavaScript
Organize and summarize common BOM operations in JavaScriptnavigator: an object that encapsulates browser configuration information

  • cookieEnabled 当前浏览器是否开启了cookie
    • cookie:在客户端的存储空间,且容量较小根据不同的浏览器有不同的大小,可以做到永久保存 密匙
    • 缺点:特别容易泄露个人信息
  • plugins 封装了浏览器安装的所有插件信息
  • userAgent 浏览器的名称,内核 版本号 等一些列的字符
  • onLine 电脑是否处于脱机状态 电脑联网了吗?
  • platform 返回运行浏览器的操作系统平台
  • appCodeName 返回浏览器的代码名
  • appName 返回浏览器的名称
  • appVersion 返回浏览器的平台和版本信息

history对象

window.history 对象包括浏览器的历史(url)集合

  • 浏览器的后退功能:history.back()
  • 浏览器的向前功能:history.forward()
  • 进入历史中的某一个页面:history.go()

screen对象

window.screen 对象包含有关用户的信息
Organize and summarize common BOM operations in JavaScript

// screen:获得显示设备的分辨率大小
// 完整的分辨率:screen.widht/height
// 如何鉴别客户端的种类 兼容所有的客户端 宽度
//      大屏        中屏            小屏            超小屏
//      lg          md               sm             xs
//      TV          pc               pad            phone
//宽  >= 1200      >=992            >= 768           
  • 可用屏幕宽度:screen.availWidth
  • 可用屏幕高度:screen.availHeight
  • 屏幕高度:screen.Height
  • 屏幕宽度:screen.Width
  • 屏幕的颜色的位数:colorDepth

元素偏移量offset系列

可以动态得到该元素的位置(偏移)、大小等

  • 获取元素距离定位父元素的位置
  • 获取元素自身大大小
  • ps:返回的数值不带单位

offset系列常用属性:

  • element.offseParent:返回作为该元素带有定位的父级元素,如果父级元素都没有定位则返回body
  • element.offsetTop*:返回元素相对带有定位父元素上方的偏移
  • element.offsetLeft*:返回元素相对带有定位父元素左方的偏移
  • element.offsetWidth:返回自身包括padding、边框、内容的宽度,不带单位
  • element.offsetHeight:返回自身包括padding、边框、内容的高度,不带单位

元素可视区client系列

动态获取元素的边框大小、元素大小等

常用属性:

  • element.clientTop:元素上边框的大小
  • element.clientLeft:元素左边框的大小
  • element.clientWidth*:返回自身包括padding、内容区的宽度,不含边框,不带单位
  • element.clientHeight*:返回自身包括padding、内容区的高度,不含边框,不带单位

元素滚动scroll系列

动态获取元素的大小、滚动距离

常用属性

  • element.srcollTop*:返回被卷去的上侧距离,不带单位
  • element.srcollLeft*:返回被卷去的左侧距离,不带单位
  • element.srcollWidth:返回自身实际的宽度,不含边框,不带单位
  • element.srcollHeight:返回自身实际的高度,不含边框,不带单位

滚动条在滚动的时候会触发onscroll事件

查看滚动条的滚动距离

window.pageXOffset/pageYOffset IE8 及IE8以下不兼容 document.body/documentElement.scrollLeft/scrollTop兼容性比较混乱,用时取两个值相加,因为不可能存在两个值同时有值 封装兼容性方法,求滚动条滚轮滚动距离getScrollOffet()

/* 
封装一个获取滚动条的滚动距离  
返回:x:水平滚动条滚动的距离  y:垂直滚动条滚动的距离
*/function getScrollOffet(){
    if(window.pageXOffset){
        return {//对象的{}一定要在关键字后,否则系统会自动加上; 则返回值会是undefined
            x : window.pageXOffset,
            y : window.pageYOffset        }
    }else{//兼容IE8以及以下
        return {
            x : document.body.scrollLeft + document.documentElement.scrollLeft,
            y : document.body.scrollTop + document.documentElement.scrollTop        }
    }}

查看视口的尺寸

window.innerWidth/innerHeightIE8及IE8以下不兼容(注意:这里的宽度和高度不包括菜单栏、工具栏以及滚动条等的高度) document.documentElement.clientWidth/clientHeight标准模式下,任意浏览器都兼容 document.body.clientWidth/clientHeight适用于怪异某事下的浏览器 封装兼容性方法,返回浏览器视口尺寸getViewportOffset()

/*封装返回浏览器视口尺寸
返回值:
    w :视口的宽度
    h : 视口的高度
*/function getViewportOffset(){
    if(window.innerWidth){
        return {
            w : window.innerWidth,
            h : window.innerHeight        }
    }else{ //兼容IE8以及以下的浏览器
        if(document.compatMode == 'BackCompat'){
            //怪异渲染模式下
            return {
                w : document.body.clientWidth,
                h : document.body.clientHeight            }
        }else{
            // 标准模式
            return {
                w : document.documentElement.clientWidth,
                h : document.documentElement.clientHeight            }
        }
    }}console.log(document.compatMode);// BackCompat 怪异模式// CSS1Compat 标准模式

查看元素的几何尺寸 ES5新增了解

domElement.getBoundingClientRect() 兼容性很好;返回一个对象,该对象中有left、top、right、bottom等属性,left、top代表元素左上角的X和Y坐标, right和bottom表示元素右下角的X和Y坐标height 和 width属性老版本IE未实现 返回的结果并不是’实时的’

// 获取元素在文档中的位置function getElementPosition(target){
    // 支持 BoundingClientRect()方法
    if(0 && target.getBoundingClientRect){
        var pos = target.getBoundingClientRect();

        return { // 涉及到滚动条有移动的情况下  加上滚动条的位置
            x : pos.left + Math.max(document.body.scrollLeft, document.documentElement.scrollLeft),
            y : pos.top + Math.max(document.body.scrollTop, document.documentElement.scrollTop)
        }
    } else {
        var pos = {
            left : 0,
            top : 0
        }
        var _elm = target;
        while(target.offsetParent){
            if(_elm == target){//首次累加left 和 top
                pos.left +=  target.offsetLeft;
                pos.top += target.offsetTop;
            }else{
                pos.left +=  target.offsetLeft + target.clientLeft;
                pos.top += target.offsetTop + target.clientTop;
            }
            // target 重新赋值
            target = target.offsetParent;
        }
        return { x : pos.left, y : pos.top}
    }}

属性

状态栏

  • defaultStatus 改变浏览器状态栏的默认显示
  • status 临时改变浏览器状态的显示

窗口位置

  • IE
    • screenLeft declares the x coordinate of the upper left corner of the window
    • screenTop declares the y coordinate of the upper left corner of the window
    • document.body.screenLeft
    • document.documentElement.screenLeft declares the number of pixels the current document has scrolled to the right
    • document.body.screenTop
    • document.documentElement.screenTop declares the number of pixels the current document has scrolled to the right Number
  • !IE
    • screenX declares the x coordinate of the upper left corner of the window
    • screenY declares the y coordinate of the upper left corner of the window
    • pageXOffset declares the number of pixels the current document has scrolled to the right
    • pageYOffset declares the number of pixels the current document has scrolled to the right
  • FF
    • innerHeight Return The height of the window's document display area
    • innerWidth Returns the width of the window's document display area
    • outerWidth Returns the window's outer width
    • outerHeight Returns the window's outer height

Other attributes

  • opener can realize communication between cross-forms under the same domain name. One form must contain the opener of another form
  • closed Returns true when the current window is closed
  • name Sets or returns the name of the window
  • self Returns a reference to the current window

[Related recommendations: javascript Video tutorialweb front-end

The above is the detailed content of Organize and summarize common BOM operations in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete