1. 程式人生 > >window物件使用總結

window物件使用總結

1、計時器
1.1、重複型計時器
var timer = setInterval(function () {//開啟定時器
if(condition){
clearInterval(timer)//取消定時器
}else{
//do
}
})
1.2、一次性計時器
setTimeout()
clearTimeout()
2、瀏覽器定位和導航
2.1、window.location === document.location
2.2、window.location = {
hash: "#hhh", //雜湊值
host: "localhost:55185", //主機名加埠號
hostname: "localhost", //主機名
href: "http://localhost:55185/javascript/2.html?_ijt=ditma9rplqkl8pm7aa3t#hhh", //url地址
origin: "http://localhost:55185", //源
pathname: "/javascript/2.html", //路徑
port: "55185", //埠號
protocol: "http:", //協議
search: "?_ijt=ditma9rpl9fpm7aa3t", //查詢字串
reload: ƒ (), //重新載入當前文件(重新整理)
assign: ƒ (), //載入替換文件
replace: ƒ () //載入替換文件並刪除當前文件瀏覽歷史
toString: ƒ toString() //將location物件轉換成等於location.href的字串
}
2.3、其他載入新文件方式
2.3.1、location.href = url
2.3.2、location = url
tip:如果只改變了hash屬性,則只在當前文件中進行跳轉
2.4、獲取查詢字串的資料
function getSearchPara() {
    var para = {}
    var search_query = location.search.substring(1)
    var pairs = search_query.split('&')
    for(var i = 0; i < pairs.length; i++){
        if(pairs[i].indexOf('=') !== -1){
            var arr = pairs[i].split('=')
            para[arr[0]] = decodeURIComponent(arr[1])
        }
    }
    
return para }

3、瀏覽歷史window.history
後退:history.back()相當於history.go(-1)
前進:history.forward()相當於history.go(1)
重新整理:history.go(0)
4、使用navigator.userAgent來進行瀏覽器嗅探
var browser = function () {
    var s = navigator.userAgent.toLowerCase();
    var match = /(webkit)[ \/]([\w.]+)/.exec(s) ||
        /(opera)(?:.*version)?[ \/]([\w.]+)/.exec(s) ||
        /(msie)([\w.]+)/.exec(s) ||
        !/compatible/.test(s) && /(mozilla)(?:.*? rv:([\w.]+))?/.exec(s) ||
        [];
    
return { name: match[1] || "", version: match[2] || "0" }; }

5、使用window.screen獲取裝置螢幕寬高
availHeight/availWidth: 瀏覽器視窗可用寬高(不包括系統工具欄)
height/width: 螢幕實際寬高
colorDepth: 24
6、瀏覽器視窗對話方塊 :alert()、confirm()、prompt()
7、利用id屬性或部分元素的name屬性查詢DOM元素
8、多視窗互動
w = window.open()
w.close()