BOM topics

BOM involving five main objects, comprising a window object, location objects, history objects, objects Navigator, screen objects.

Part of javascript:

  • DOM (document object model) Document Object Model
  • BOM (browers object model) browser object model
  • The core of the ECMAScript js

DOM is a set of standards, DOM1 / 2/3, is now commonly used DOM2 / 3. ECMAScript is also standard, but there is no label BOM itself, in all its browsers are not necessarily compatible.

1.window objects

- innerWidth/innerHeight
- open 方法

window.open(URL,target,specs,replace)  
  - URL 新窗口地址
  - target 属性 新窗口打开方式
    - _blank
    - _self 
  - specs 新窗口规格
    - width=pixels	窗口的宽度.最小.值为100
    - height=pixels	窗口的高度。最小.值为100
    - location=yes|no|1|0	是否显示地址字段.默认值是yes
    - menubar=yes|no|1|0	是否显示菜单栏.默认值是yes
    - resizable=yes|no|1|0	是否可调整窗口大小.默认值是yes
    - scrollbars=yes|no|1|0	是否显示滚动条.默认值是yes
    - status=yes|no|1|0	是否要添加一个状态栏.默认值是yes
    - titlebar=yes|no|1|0	是否显示标题栏.被忽略,除非调用HTML应用程序或一个值得信赖的对话框.默认值是yes
    - toolbar=yes|no|1|0	是否显示浏览器工具栏.默认值是yes
- close 方法关闭窗口

- scroll 事件
- resize 事件
- 操作滚动条位置
  - window.scrollX、window.scrollY、window.scrollTo()
  - document.documentElment.scrollTop、document.documentElment.scrollLeft

- window 下的各类弹窗
  - alert()
  - confirm('message')
  - prompt([msg],[defaultText])

innerWidth / innerHeight under 1.1 window

  • window.innerWidth visible region width
  • window.innerHeight highly visible area

High visible region width (width and height of the visible browser) method of high shrinkage relaxation inconsistent depending on the browser. The method call window, window omitted Jieke

console.log(window.innerWidth,window.innerHeight);
console.log(innerWidth,innerHeight);

 open () / close () 1.2 window in the method

open () method to open a new window. Because some malicious pop, can some of the current version of the browser will prevent new window generation.

window.open(URL,target,specs,replace):

  1. Three parameters:
  2. New window URL address;
  3. The target property New windows open: _blank opens a new window; _self opens in the current window; the other way is now open a basic need
  4. specs new window specification (compatibility is not good to use a comma between each parameter.):
  • - width = minimum value of the window width of 100 pixels.
  • - height = height of the pixels of the window. Minimum. Value 100
  • - location = yes | no | 1 | 0 whether to display the address field default is yes.
  • - menubar = yes | no | 1 | 0 whether to display the menu bar, the default value is yes.
  • - resizable = yes | no | 1 | 0 whether to adjust the window size default is yes.
  • - scrollbars = yes | no | 1 | 0 whether to display the scroll bar default is yes.
  • - status = yes | no | 1 | 0 Whether you want to add a status bar default is yes.
  • - titlebar = yes | no | 1 | 0 whether the title bar is ignored, unless you call HTML application or a trusted dialog box, the default is yes..
  • - toolbar = yes | no | 1 | 0 whether to display the browser toolbar default is yes.

window.close () method to close the window. Note: This window must be open window record, if used directly window.close () will open a new window and the original window close together.

    let btn = document.querySelector("button");
    btn.onclick = () =>{
        let win = window.open("http://www.baidu.com","_blank","width=400px,height=400px,location=no");

        //window.close关闭窗口
        setTimeout(()=>{
            win.close();
        },3000);
    };

All kinds of pop at 1.3 window 

The actual project these methods use less, because the style ugly.

  1. alert (): Click the pop-up prompt message
  2. confirm ( 'message'): Click OK to return true, click Cancel to return false
  3. prompt ([msg], [defaultText]): can be input. The first parameter: message; second parameter: the text box default; Return Value: text box to enter content
    // alert("弹出消息");
    // confirm("是否删除信息");
    let val = prompt("你今天锻炼了吗?","打羽毛球");
    console.log(val);//打羽毛球,兵乓球

1.4 onscroll event / onresize event / Get and set the scroll bar position

  • Get their element width and height: offsetWidth, offsetHeight
  • Get visible region width and height: innerWidth, innerHeight
  • onscroll event: the scroll bar to scroll trigger
  • window.onresize event: when the trigger window scaling, listening window size changes
  • Obtaining position of the scrollbar: window.scrollY obtaining longitudinal position of the slider; window.scrollX obtaining horizontal scroll position; window.scroll (x, y) position and set the horizontal and vertical scroll bars (Chrome / Firefox / mobile terminal)
  • Obtaining the position of the scrollbar IE: document.body.scrollLeft Get horizontal scroll bar position and longitudinal position of the slider acquired document.body.scrollTop
  • If only document.body.scrollLeft and document.body.scrollTop then in chrome and other browsers will get less, we need to set the compatibility document.documentElement.scrollLeft and document.documentElement.scrollTop
  • So generally acquires the position of the scrollbar: let scrollTop = document.documentElement.scrollTop || ocument.body.scrollTop; let scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
  • Set position of the scrollbar: document.documentElement.scrollTop = ocument.body.scrollTop = position; document.documentElement.scrollLeft = document.body.scrollLeft = position;
  • When the scroll bar to scroll, slightly beating each browser performance is due to the problems caused. And judgment between the position of the scrollbar If you have trouble beating a great location that is set element

Centered advertising pop: fixed positioning can be achieved; + absolute positioning here using the scroll bar position to achieve

In the visible region centered pop: / 2 and (-ad entire width of the viewable area popups width) from the top (the height of the entire height -ad pop visible region) distance from the left / 2

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        div {
            height: 200px;
            width: 2000px;
            border: 1px solid black;
        }
        #ad {
            width: 200px;
            height: 200px;
            background: black;
            color: white;
            font: 30px/200px "宋体";
            text-align: center;
            position: absolute;
            top: 0;
            left: 0;
        }
    </style>
</head>
<body>
    <div id="ad">这是一个广告</div>
    <div>1</div><div>1</div><div>1</div><div>1</div><div>1</div><div>1</div><div>1</div><div>1</div><div>1</div><div>1</div><div>1</div><div>1</div><div>1</div><div>1</div><div>1</div><div>1</div>
<script>
    //需求:将广告定位到浏览器正中间。拖动滚动条和缩放窗口时,仍然保持中心位置
{
    let ad = document.querySelector("#ad");
    //弹窗在可视区:居中:距离顶部的距离(整个可视区高度-ad弹窗高度)/2和距离左侧距离(整个可视区宽度-ad弹窗宽度的)/2
    //浏览器可视区宽高
    // let windowW = innerWidth;
    // let windowH = innerHeight;

    //广告弹窗本身宽高
    // let adW  = ad.offsetWidth;
    // let adH = ad.offsetHeight;

    let setPos = ()=>{
        //设置决定定位位置
        let l = (innerWidth-ad.offsetWidth)/2;
        let t = (innerHeight-ad.offsetHeight)/2;

        //获取滚动条位置:在滚动条滚动时,加上滚动条位置即可居中
        let scrollL = document.documentElement.scrollLeft || document.body.scrollLeft;
        let scrollT = document.documentElement.scrollTop || document.body.scrollTop;

        ad.style.left = l + scrollL + "px";
        ad.style.top = t + scrollT + "px";
    }
    //页面第一次刷新时设置定位
    setPos();

    //监听到窗口缩放时,需要设置
    window.onresize = () =>{
        setPos();
    };

    //监听到滚动条位置发生变化时,需要设置
    window.onscroll = () =>{
        setPos();
    };
    
}
</script>
</body>
</html>

 

If you need to solve a slight shake when the scroll bar to move and zoom window problem, you can add animation effects:

//监听到窗口缩放时,需要设置
    window.onresize = () =>{
        ad.style.transition = "1s";
        setPos();
    };

    //监听到滚动条位置发生变化时,需要设置
    window.onscroll = () =>{
        ad.style.transition = "1s";
        setPos();
    };

 

2.location objects

  • - hash   
  • - hashChange
  • - search
  • - reload()
  • - replace()

2.1location Object Overview

  1. host: the host name / domain name + port
  2. hostname: the host name / domain name + port. 80 default port if the port 80 is not displayed, the server settings;
  3. port: port number
  4. href: complete address. Get request data including the hash value and
  5. origin:
  6. pathname: The path to the server project
  7. protocol: Protocol, the main http and https
  8. hash:
  9. search: submission on behalf of the data get over. Such as:? kkb = Starting now. data submitted to obtain the address bar post less. There hash value, but also get less than

Example: Access https://www.lyblog.net/category/webfront.html , enter the location in the console:

2.2location focus on an object method resolution

  1. location.href: Complete information on the address bar, you can get both can also be set
  2. the location.replace () :  replace the address bar information. Href and the like, but do not use the same
  3. location.reload: refresh the page. You can also use location.href = location.href refresh
  4. location.hash : behind the content of the address #

location.href: Complete information on the address bar, you can get both can also be set

<body>
    <button>跳转</button>
<script>
{
    let btn = document.querySelector("button");
    btn.onclick = ()=>{
        //获取href信息
        console.log(location.href);//file:///E:/StudyFile/kaikeba/works/BOM%E4%B8%93%E9%A2%98/location.href.html
        location.href = "https://www.baidu.com/s?wd=开课吧"
    };

}
</script>
</body>

the location.replace () :  replace the address bar information. Href and the like, but do not use the same

 let btn = document.querySelector("button");
    btn.onclick = ()=>{
        location.replace("https://www.baidu.com/s?wd=开课吧");
    };

location.reload: Refresh the page

<body>
    <button>刷新</button>
<script>
{
    let btn = document.querySelector("button");
    btn.onclick = ()=>{
        // location.reload();
        location.href = location.href;
    };

}
</script>
</body>

2.3 location.hash routing implementation principle 

Routing (routing) refers to the process when a packet from a source to a destination, the network-end path determined range.

JS hash routing of: a front end view displayed is determined according to the path . The anchor point is equivalent to css

onhashchange: monitor changes in the location of hash

vue and hash-router react in the realization of the principle is based on hash

Demand: first time the page refreshes and # view1, display view1; # view2 display view2; # view3 display view3

<body>
    <a href="#view1">视图1</a>
    <a href="#view2">视图2</a>
    <a href="#view3">视图3</a>
    <div id="view">这是第一个视图</div>
<script>
{
    let view = document.querySelector("#view");
    let setView = ()=>{
        let hash = location.hash;
        console.log(hash);
        
        switch(hash){
            case "":
            case "#view1":
                view.innerHTML = '这是第一个视图';
                break;
            case "#view2":
                view.innerHTML = '这是第二个视图';
                break;
            case "#view3":
                view.innerHTML = '这是第三个视图';
                break;
            default:
                view.innerHTML = '这是第一个视图';
        }
    };
    window.onhashchange = setView;
}

3.history objects

  • - back (): Returns the history of the previous step
  • - forward (): Returns the next step in history
  • - go (): Jump to a certain step. A negative number indicates rollback, integer back.
  • - state
  • - pushState()
  • - popstate
  • - history routing implementation principle

3.1 back()/forward()/go():

Back to History of the previous step, the next step or a designated

    <a href="history_1.html">视图1</a>
    <a href="history_2.html">视图2</a>
    <a href="history_3.html">视图3</a>
    <br>
    <button>跳转到</button>
    <input type="text">
    <button>上一页</button>
    <button>下一页</button>
    <div>这个第一页</div>
<script>
{
    let btn = document.querySelectorAll("button");
    btn[0].onclick = () =>{
        let page = document.querySelector("input");
        history.go(parseInt(page.value));
    };
    btn[1].onclick = () =>{
        // history.go(-1);
        history.back();//上一页
    };
    btn[2].onclick = () =>{
        // history.go(-1);
        history.forward();//下一页
    };
}

3.2 history to achieve the object routing principles

  • -state
  • - pushState()
  • - popstate
  • - history routing implementation principle

The principle route history :

  1. You must disable the original page jump function;
  2. You must use with the server environment

history.pushState () method : used to set the address corresponding to the template switching.

history.pushState () method parameters :

  1. Carried out after obtaining: {val name}, generally used for traditional values, forward and back buttons and clicking on the browser window.onpopstate first parameter may be an object
  2. The second parameter title, there is little substantive role
  3. The third parameter history state value, i.e., each template corresponding address url

window.onpopstate event : the upper and lower switching event history - click on the entry into force forward and back button on the browser after

Implement static routing using history page switching , example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        li {
            margin: 10px;
        }
    </style>
</head>
<body>
<div id="view">
    <ul>
        <li><a href="/index">首页</a></li>
        <li><a href="/about">关于我们</a></li>
        <li><a href="/details">详细介绍</a></li>
    </ul>
    <div id="cont"></div>
</div>
<script>
{
    /*
        history路由实现原理:
            1:必须禁用原来的跳转功能;
            2:必须配合服务器环境下使用
    */
    let view = document.querySelector("#view");
    let ul = document.querySelector("ul");
    let allA = document.querySelectorAll("ul a");
    let cont = document.querySelector("#cont");
    
    let indexRender = ()=>{
    	return `
    		<p>这是首页相关信息</p>
    	`;
    }
    let aboutRender = ()=>{
    	return `
    		<p>这是关于我们相关信息</p>
    	`;
    }
    let detailsRender = ()=>{
    	return `
    		<p>这是详细介绍相关信息</p>
    	`;
    }
    
    let matching =()=>{
    	let path = location.pathname;
        console.log(location.pathname);
    	switch(path){
    		case "/UnionpayDemo/":
    		case "/index":
    			cont.innerHTML = indexRender();
    			break;
    		case "/about":
    			cont.innerHTML = aboutRender();
    			break;
    		case "/details":
    			cont.innerHTML = detailsRender();
    			break;
    	}
    }
    //页面一开始刷新时也要显示默认页面
    matching();
    allA.forEach(item=>{
        item.onclick = function(){
            /*
               	 切换对应的模板地址:history.pushState()方法
                    history.pushState()方法参数
                        第一个参数 可以为一个对象{ name:val},一般用于传值,并可在window.onpopstate 点击浏览器上 前进后退按钮后进行获取
                        第二个参数 title,基本没有什么实质作用
                        第三个参数 history状态值,即每个url对应的模板地址
            */
            console.log(item.href);
            history.pushState({info:'lmf',age:18},"history路由实现原理",item.href);
            matching();
            //注意return false阻止浏览器默认事件,只能用于绑定事件不能用于事件监听
            return false;
        }
    });
    
    // 历史记录上下切换事件 - 浏览器上 前进后退按钮
    window.onpopstate = function(){
        // 获取history传递过来的值
        console.log(history.state)
        matching();
    }
}
</script>
</body>
</html>

Since the server coding problems caused garbled. But it does not affect the results. 

4. navigator objects

  • - userAgent
  • - appName
  • - appVersion

4.1navigator Object Overview

Store some information about the device and browser.

  • appCodeName: Return code name of the browser. All with Netscape code-based browser, its value is "Mozilla". For compatibility reasons, Microsoft's browser, its value is "Mozilla".
  • appName : Returns the name of the browser.
  • appVersion : Returns the platform and version information of the browser.
  • onLine : returns a Boolean value that indicates whether the system is in offline mode.
  • the userAgent : Returns the value of the user-agent header sent by the client server.
  • BrowserLanguage : Returns the current language of the browser.
  • cookieEnabled : returns a Boolean value indicating whether the browser to enable cookie.

4.2 navigator的userAgent(**)

Determine whether the PC :

function IsPC() {
    var userAgentInfo = navigator.userAgent;
    var Agents = ["Android", "iPhone",
                "SymbianOS", "Windows Phone",
                "iPad", "iPod"];
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false;
            break;
        }
    }
    return flag;
}

Judgment means (Andrews or Apple (iPad is Apple a)):

var ua = navigator.userAgent.toLowerCase();
if (/android|adr/gi.test(ua)) {
    // 安卓
     
}else if(/iPad/gi.test(ua)){
    //iPad

}else if(/\(i[^;]+;( U;)? CPU.+Mac OS X/gi.test(ua)){
    //苹果
     
}

Analyzing different clients : Sina Bo 1, QQ client 2, the micro-channel is less than 3 6.0.2, 6.0.2 is higher than 4, and 0 otherwise.

var ua = navigator.userAgent.toLowerCase();  
if(ua.match(/weibo/i) == "weibo"){  
    console.log(1);
}else if(ua.indexOf('qq/')!= -1){  
    console.log(2);
}else if(ua.match(/MicroMessenger/i)=="micromessenger"){  
var v_weixin = ua.split('micromessenger')[1];  
    v_weixin = v_weixin.substring(1,6);  
    v_weixin = v_weixin.split(' ')[0];  
if(v_weixin.split('.').length == 2){  
    v_weixin = v_weixin + '.0';  
}  
if(v_weixin < '6.0.2'){  
    console.log(3);
}else{  
    console.log(4);  
}  
}else{  
    console.log(0); 
}

To distinguish individual browsers :

var ua=navigator.userAgent.toLowerCase();  
if(/msie/i.test(ua) && !/opera/.test(ua)){  
    alert("IE");  
    return ;  
}else if(/firefox/i.test(ua)){  
    alert("Firefox");  
    return ;  
}else if(/chrome/i.test(ua) && /webkit/i.test(ua) && /mozilla/i.test(ua)){  
    alert("Chrome");  
    return ;  
}else if(/opera/i.test(ua)){  
    alert("Opera");  
    return ;  
} else if(/webkit/i.test(ua) &&!(/chrome/i.test(ua) && /webkit/i.test(ua) && /mozilla/i.test(ua))){  
    alert("Safari");  
    return ;  
}else{  
    alert("unKnow");  
}

5.screen objects

Get the width and height of the screen: width, height

Published 95 original articles · won praise 115 · views 120 000 +

Guess you like

Origin blog.csdn.net/qq_34569497/article/details/98616010