0
我有以下代码,检查加载/调整大小的窗口和accroding变量MOBILE_WIDTH
它运行(或不)该函数。但是,它遵循一个明显的问题,即重新启动相同的函数时,它会重新执行每个初始化内容,例如.forEach方法,所以当我们在调整控制台日志的大小后单击同一标题时,显示我们多次单击它。如何避免这种情况? 和codepen here。重新使用窗口调整大小/加载功能
let window_handlers = ['load', 'resize'];
let h1 = document.querySelectorAll('h1');
const MOBILE_WIDTH = 600;
window_handlers.map(handler => {
\t window.addEventListener(handler,()=>{
\t \t console.log(handler)
\t \t if(window.innerWidth <= MOBILE_WIDTH) { \t \t \t
\t \t \t test(true);
\t \t } else {
\t \t \t test(false);
\t \t }
\t })
})
let test = (statement) => {
\t if(statement) {
\t \t Array.from(h1).forEach(element => {
\t \t \t element.addEventListener('click',()=> {
\t \t \t \t console.log('clicked')
\t \t \t })
\t \t })
\t }
}
* {
box-sizing: border-box;
}
html, body {
height: 100%;
}
body {
font-family: "Roboto", sans-serif;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
background-color: #FE5F55;
}
h1 {
font-size: 32px;
font-weight: bold;
cursor: pointer;
color: white;
margin-bottom: 10px;
-webkit-transition: .3s;
transition: .3s;
text-shadow: 2px 2px rgba(255, 255, 255, 0.4), 4px 4px rgba(0, 0, 0, 0.1);
}
h1:hover {
text-shadow: 1px 1px rgba(255, 255, 255, 0.4), 2px 2px rgba(0, 0, 0, 0.1);
}
<div class="headers">
\t <h1>Header 1</h1>
\t <h1>Header 2</h1>
</div>
点击事件就是一个例子,代码由更多的功能组成。我不希望它只取代点击事件。 – NeedHate
这种方法对于你在那里的每个听众都是一样的 – gugateider
有两个forEach方法,它们不是事件监听器。 – NeedHate