javascript - 即使不重新加载页面,如何使用 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");
}
解决方案
您可以在事件发生后检查大小,而不是一直删除和添加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();
}
});
推荐阅读
- javascript - 如何在 React 中的 onClick 事件之后插入新的 HTML 语法
- flutter - 如何在 Flutter 中独立设置位于另一个字母上方的泰语字母?
- c# - 实体框架自定义类型作为属性
- python - Raspberry PI 使用 TensorflowLite 进行慢速预测
- flutter - PageView.builder 中的多个表单验证
- java - 在3中找到最大的数字,我在最后一部分遇到了粗体字的问题
- javascript - TypeError:无法读取 null 的属性“blockNumber”
- reactjs - 在 React App 中使用什么 Material-UI 或 Semantic UI
- android - 向布局容器中删除和添加新子项时如何延迟 Android UI 更新?
- groovy - Groovy 元编程——我应该把它放在哪里?