简体   繁体   English

javascript 全局变量好习惯

[英]javascript global variable good practice

I have a few variables pertaining to the height of elements an want to update them using $(window).on('resize'[...]), as well as calculate them when first loading the page so naturally I would rather make a function for doing that, instead of repeating the code.我有一些与元素高度有关的变量,我想使用$(window).on('resize'[...]),并在第一次加载页面时计算它们,所以我很自然地宁愿做一个 function 这样做,而不是重复代码。

Is it bad practice to make these variables global so that I can update them with a function, or is there any other way to do this?将这些变量设为全局变量以便我可以使用 function 更新它们是不好的做法,还是有其他方法可以做到这一点?

    var hSum = 0
    for (var i = 0; i < content.length; i++) {
        var contentH = $(content[i]).height()
        hSum += contentH
    }

    var windowHeight = $(window).height(),
        footerHeight = footer.height(),
        heightDocument = windowHeight + hSum + footer.height() - 20;

This is the entirety of the script这是整个脚本

function scrollFooter(scrollY, footerHeight) {

    if (scrollY >= footerHeight) {
        $('footer').css({
            'bottom': '0px'
        });
    } else {
        $('footer').css({
            'bottom': '-' + footerHeight + 'px'
        });
    }
}

$(document).ready(function() {
    var content = $('.content'),
        header = $('header'),
        footer = $('footer'),
        headerContainer = header.find('.container'),
        headerBackground = header.find('.background'),
        nav = $('.navbar')

    var hSum = 0
    for (var i = 0; i < content.length; i++) {
        var contentH = $(content[i]).height()
        hSum += contentH
    }

    var windowHeight = $(window).height(),
        footerHeight = footer.height(),
        documentHeight = windowHeight + hSum + footer.height() - 20;


    $('#scroll-animate, #scroll-animate-main').css({
        'height': documentHeight + 'px'
    })

    $('header').css({
        'height': windowHeight + 'px'
    })

    $('.wrapper-parallax').css({
        'margin-top': windowHeight + 'px'
    })

    scrollFooter(window.scrollY, footerHeight);

    setTimeout(function fadeHeaderIn() {
        headerContainer.css('opacity', '1')
        headerBackground.css('transform', 'scale(1.25, 1.25)')
    }, 300)


    $(window).on('scroll', function() {
        scroll = window.scrollY

        $('#scroll-animate-main').css({
            'top': '-' + scroll + 'px'
        });

        scrollFooter(scroll, footerHeight);

        nav.toggleClass('hidden', scroll < windowHeight)
    })

    nav.on("mouseenter", function() {
        nav.removeClass('minimized')
    })

    nav.on("mouseleave", function() {
        nav.addClass('minimized')
    })

    $('.navbutton').on('click', function(event) {
        if ($(this).attr('href') == "#contact")
            $('html, body').stop().animate({ scrollTop: documentHeight }, 300, 'swing')
        else $('html, body').stop().animate({ scrollTop: $($(this).attr('href')).offset().top }, 300, 'swing')
        event.preventDefault()

    })
})

The best thing to do is to create a class to handle all the element functions.最好的办法是创建一个 class 来处理所有元素功能。

for example, let's assume that you have a div or a canvas that you want to check for it's size.例如,假设您有一个要检查其大小的 div 或 canvas。

 function divHandler(divID){ this.div = document.getElementById(divID); //Add all global variables here this.boundingRect = this.div.getBoundingClientRect() } //After that access the variables by other functions divHandler.prototype.displayData = function(){ console.log(this.boundingRect); } const d = new divHandler('someDiv'); d.displayData();
 #someDiv{ min-width: 100px; min-height: 100px; border: 1px solid black; }
 <div id="someDiv"> </div>

Now you have a class that controls all divs by id and you can use it again and again for all other divs in the code.现在你有了一个 class ,它通过 id 控制所有 div,你可以一次又一次地将它用于代码中的所有其他 div。

Update 1:更新 1:

You can also add an event listener like this 您还可以像这样添加事件侦听器

 function divHandler(divID){ this.div = document.getElementById(divID); //Add all global variables here this.boundingRect = this.div.getBoundingClientRect() } divHandler.prototype.listen = function (event, cb, ...args){ this.div.addEventListener(event,cb.bind(this, ...args)); } const d = new divHandler('someDiv'); d.listen('click', function(e){ console.log(e.type); this.div.style.backgroundColor = "blue" });
 #someDiv{ min-width: 100px; min-height: 100px; border: 1px solid black; }
 <div id="someDiv"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM