0

在我的javascript代码中,我正在获取正文的宽度并检查正文的宽度是否为特定值,然后从元素中添加或删除onclick函数但是当我减小/增加页面的大小时,onclick函数不会添加/remove 分别根据我只想记录正文宽度的条件,以便在不重新加载页面的情况下 onclick 函数从元素中添加/删除。

     let body = document.querySelector(".body");
     let bodyWidth = body.offsetWidth;
     if (bodyWidth < 785) {
        var myOpener = false;
    document.querySelector("#contact- 
    h2").setAttribute("onclick","openTheContact()");
        document.querySelector("#service- 
    h2").setAttribute("onclick","openTheServices()");
    }
     if (bodyWidth > 785) {
        document.querySelector("#contact-h2").removeAttribute("onclick");
        document.querySelector("#service-h2").removeAttribute("onclick");
     }
4

2 回答 2

2

您可以在事件发生后检查大小,而不是一直删除和添加click

function isWindowSmall() {
    return window.innerWidth <= 785;
}

document.querySelector('#contact-h2').addEventListener('click', function () {
    if (isWindowSmall()) {
        openTheContact();
    }
});

document.querySelector('#service-h2').addEventListener('click', function () {
    if (isWindowSmall()) {
        openTheServices();
    }
});
于 2019-08-01T06:37:17.193 回答
-1

你应该尝试这样的事情。使用 onresize 事件。

window.onresize=function(){
let body = document.querySelector(".body");
     let bodyWidth = body.offsetWidth;
     console.log("bodyWidth"+bodyWidth)
     if (bodyWidth < 785) {
        var myOpener = false;
    document.querySelector("#contact-h2").setAttribute("onclick","openTheContact()");
        document.querySelector("#service-h2").setAttribute("onclick","openTheServices()");
    }
     if (bodyWidth > 785) {
        document.querySelector("#contact-h2").removeAttribute("onclick");
        document.querySelector("#service-h2").removeAttribute("onclick");
     }
}
于 2019-08-01T06:25:11.923 回答