如何通过 svg 路径和多边形以比 .each 更快的速度循环



我正在绘制不同的svg地图。每个国家都会淡入淡出。下面我单击#compbtn按钮以使用.compbtn加载.compMap地图。然而,在处理和开始每个多边形和路径的淡入淡出之前,.each似乎真的很慢。

如何比使用.each循环更快?

.html

<div class="oldmap">SVG old map polygons and path</div>
<div class="newmap">SVG old map polygons and path</div>
<div class="computer_all">SVG old map polygons and path</div>

注意:.country.shape是我用于每个部分的顺序淡入淡出的多边形和路径类。

.JS

$("#compbtn").on("click", function(i) {
  var $newMap =$('.newmap .country, .newmmap .shape');
  $newMap.each(function( i ){
    $(this).delay(2*i).fadeTo(300,0);
  });
  var $oldmap = $('.oldmap .country, .oldmap .shape');
  $oldmap.each(function( c ){
    $(this).delay(2*c).fadeTo(300,0);
  });
  var lis = $('.computer_all .country, .computer_all .shape'),
  len = lis.length;
  lis.each(function(b) {
    $(this).delay(2*b).fadeTo(500,1, function(){
      if (b === len - 1) {
        $(".oldmap").css("left", "-9999px");
        $(".newmap").css("left", "-9999px");
      }
    });
  });
});

这种效果可以用(大部分)CSS来完成吗?如果我这样做,我会遍历每个形状,并在 JavaScript 加载时通过 style 属性设置它们的自定义 transition-delay 属性,并在样式表中使用 CSS 选择器,例如 .oldmap.out .shape.computer_all.in .shape,因此您只需使用 jQuery 编辑映射的标记,即可触发它们各自的延迟的所有淡入淡出效果。这完全避免了使用 for 循环(至少当您需要过渡时)。

.CSS:

.newmap .country,
.newmap .shape,
.oldmap .country,
.oldmap .shape {
  opacity: 1;
  transition-property: opacity;
  transition-duration: 0.3s;
}
.newmap.out .country,
.newmap.out .shape,
.oldmap.out .country,
.oldmap.out .shape {
  opacity: 0;
}
.computer_all .country,
.computer_all .shape {
  opacity: 0;
  transition-property: opacity;
  transition-duration: 0.5s;
}
.computer_all.in .country,
.computer_all.in .shape {
  opacity: 1;
}

启动:

$('.newmap .country, .newmmap .shape').each(function(i) {
  $(this).css('transition-delay', i/500 + 's');
});
$('.oldmap .country, .oldmap .shape').each(function(i) {
  $(this).css('transition-delay', i/500 + 's');
});
$('.computer_all .country, .computer_all .shape').each(function(i) {
  $(this).css('transition-delay', i/500 + 's');
});

点击:

$('#compbtn').click(function() {
  $('.newmap, .oldmap').addClass('out');
  $('.computer_all').addClass('in');
});

最新更新