簡體   English   中英

jQuery優化代碼模式

[英]jQuery optimise code patterns

下午都

我有2個jQuery代碼塊,其中有很多重復的代碼...我想知道是否有任何方法可以在行和/或性能方面簡化它。

2個塊如下:

$("#intro").css('min-height',$(window).height()-88);
$("#trabalhos").css('min-height',$(window).height()-88);
$("#fotografia").css('min-height',$(window).height()-88);
$("#cv").css('min-height',$(window).height()-88);
$("#contactos").css('min-height',$(window).height()-88);

和:

$('.portfolio').click(function(e){ e.preventDefault();$('html,body').animate({scrollTop: $('#portfolio').offset().top-88},'slow'); });
$('.cv').click(function(e){ e.preventDefault();$('html,body').animate({scrollTop: $('#cv').offset().top-88},'slow'); });
$('.trabalhos').click(function(e){ e.preventDefault();$('html,body').animate({scrollTop: $('#trabalhos').offset().top-88},'slow'); });
$('.fotografia').click(function(e){ e.preventDefault();$('html,body').animate({scrollTop: $('#fotografia').offset().top-88},'slow'); });
$('.contactos').click(function(e){ e.preventDefault();$('html,body').animate({scrollTop: $('#contactos').offset().top-88},'slow'); });

您可以將選擇器組合為單個語句,並用逗號分隔它們。

$('#intro, #trabalhos, #fotografia, #cv, #contactos').css('min-height',$(window).height()-88);

您可以使用多個選擇器組合代碼

$("#intro,#trabalhos,#fotografia,#cv,#contactos").css('min-height', $(window).height() - 88);

$('.portfolio,.cv,.trabalhos,.fotografia,.contractos').click(function(e) {
    e.preventDefault();
    $('html,body').animate({
        scrollTop: $('#'+$(this).attr('class')).offset().top - 88; // <-- this assuming you only have one class
    }, 'slow');
});

為您使用相同的CSS的ID給他們一個共同的類,然后

     $(".common_class").css('min-height',$(window).height()-88);


  is it OK.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM