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