【发布时间】:2017-07-04 04:00:09
【问题描述】:
这是我的 javascript 代码:
(function(){
"use strict";
document.addEventListener("DOMContentLoaded",animations); /*on content loaded */
function animations() {
/*start of animation for the toggle navigation button in smaller view ports*/
(function () {
var button = document.getElementById('nav-icon');
button.addEventListener('click', function(){
if (this.classList.contains('active')===true) {
this.classList.remove('active');
}
else {
this.classList.add('active');
}
})
})(); /*End of the toggle navigation animation*/
/*Start of scrolling side navigation for smaller view ports*/
(function(){
var button = document.getElementById('nav-icon');
var body = document.querySelector('body');
button.addEventListener('click', function(){
if (this.classList.contains('active')===true) {
body.classList.add('active-nav');
}
else {
body.classList.remove('active-nav');
}
});
})(); /*End of scrolling side navigation*/
(function () {
// body...
var media = window.matchMedia("(min-width: 992px)");
var body = document.querySelector('body');
var button = document.getElementById('nav-icon');
window.addEventListener('resize',function(){
if (media.matches) {
body.classList.remove('active-nav');
if (button.classList.contains('active')===true) {
button.classList.remove('active');
}
}
});
})();
};
})();
如您所见,我在代码中多次声明了具有完全相同值的变量,但它们位于不同的函数中。每个 iife 都是一个单独的动画,并且具有不同的功能,尽管它们可能共享共同的元素。但是,我想知道这是否是一个好习惯。我应该在主函数中声明公共变量,以便它们可能在所有子函数的执行上下文中吗?另外,请强调任何看起来不好或不是好的做法。谢谢
【问题讨论】:
-
这不是坏习惯,但是,例如
var body = document.querySelector('body');可以简单地写成var body = document.body; -
不知道谢谢!
标签: javascript