首页 > 解决方案 > 即使不重新加载页面,如何使用 javascript 继续记录元素的高度

问题描述

在我的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");
     }

标签: javascripthtml

解决方案


您可以在事件发生后检查大小,而不是一直删除和添加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();
    }
});

推荐阅读