簡體   English   中英

javascript 全局變量好習慣

[英]javascript global variable good practice

我有一些與元素高度有關的變量,我想使用$(window).on('resize'[...]),並在第一次加載頁面時計算它們,所以我很自然地寧願做一個 function 這樣做,而不是重復代碼。

將這些變量設為全局變量以便我可以使用 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;

這是整個腳本

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()

    })
})

最好的辦法是創建一個 class 來處理所有元素功能。

例如,假設您有一個要檢查其大小的 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>

現在你有了一個 class ,它通過 id 控制所有 div,你可以一次又一次地將它用於代碼中的所有其他 div。

更新 1:

您還可以像這樣添加事件偵聽器

 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