window常用方法

window.top

 

 當B嵌套在A頁面中時,直接是不能調用A頁面的方法和屬性的

如果想使用A頁面中的方法和屬性 可以使用window.top (返回窗口層級最頂層窗口的引用)

if(window.top != window.self) {
  window.top.location.href = window.location.href;
window.top.oepn = window.open }

 

當在iframe內時, 直接window.location.href 會打開iframe內的網站,  要解決這個問題 使用window.top.location.href = xxx 或者 window.top.open('xxx') 

window.alert

代碼

window.alert = alert;
//重寫alert
function alert (data, callback) { //回調函數
    var alert_bg = document.createElement('div'),
    alert_box = document.createElement('div'),
        alert_text = document.createElement('div'),
        alert_btn = document.createElement('div'),
        textNode = document.createTextNode(data ? data : ''),
        btnText = document.createTextNode('確 定');

    // 控制樣式
    css(alert_bg, {
        'position': 'fixed',
        'top': '0',
        'left': '0',
        'right': '0',
        'bottom': '0',
        'background-color': 'rgba(0, 0, 0, 0.1)',
        'z-index': '999999999'
    });

    css(alert_box, {
        'width': '270px',
        'max-width': '90%',
        'font-size': '16px',
        'text-align': 'center',
        'background-color': '#fff',
        'border-radius': '15px',
        'position': 'absolute',
        'top': '50%',
        'left': '50%',
        'transform': 'translate(-50%, -50%)'
    });

    css(alert_text, {
        'padding': '30px 15px',
        'border-bottom': '1px solid #ddd'
    });

    css(alert_btn, {
        'padding': '10px 0',
        'color': '#007aff',
        'font-weight': '600',
        'cursor': 'pointer'
    });

    // 內部結構套入
    alert_text.appendChild(textNode);
    alert_btn.appendChild(btnText);
    alert_box.appendChild(alert_text);
    alert_box.appendChild(alert_btn);
    alert_bg.appendChild(alert_box);

    // 整體顯示到頁面內
    document.getElementsByTagName('body')[0].appendChild(alert_bg);

    // 確定綁定點擊事件刪除標籤
    alert_btn.onclick = function () {
        alert_bg.parentNode.removeChild(alert_bg);
        if (typeof callback === 'function') {
            callback(); //回調
        }
    }
}
function css (targetObj, cssObj) {
    var str = targetObj.getAttribute("style") ? targetObj.getAttribute('style') : '';
    for (var i in cssObj) {
        str += i + ':' + cssObj[i] + ';';
    }
    targetObj.style.cssText = str;
}

 

使用

alert('發現新版本,請更新!', callback)

 

window.oepn 和 window.opener.location.reload()

通過window.open('https://www.baidu.com', '_blank', "width=300"); 打開一個新的子窗口
通過window.opener.location.reload(); 刷新父窗口頁面

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章