另一个图像滑块jQuery问题



我已经尝试了一段时间。我已经提出了图像滑块问题。但是,如果我在这里得到一些具体的帮助,我真的很感激。请告诉我以下代码在哪里出错。

这是我的jQuery代码:

function slideMe {
  $('.imgcontainer').animate({"margin-left":"-= 100%"}, 2000, function () {
   if($('.imgcontainer').css("margin-left") == (-300%)) {
     $('.imgcontainer').css("margin-left", "0px");
   }
   slideMe();
  });
}
window.onload = slideMe();

这是HTML页面上的脚本:

<div class="fitimage">
    <div class="imgcontainer">
     <img src="img/copywrtng.jpg" class="headerimage" alt="copywriting" />
     <img src="img/copywrtng1.jpg" class="headerimage" alt="copywriting" />
     <img src="img/copywrtng2.jpg" class="headerimage" alt="copywriting" />
    </div>
</div>

这是我在CSS上拥有的:

div.fitimage {
    width:100%;
    height:93vh;
    overflow: hidden;
}
img.headerimage {
    padding: 0;
    margin:0 auto;
    width:100%;
  /*max-height:100%;
    max-width:100%;*/
    height:93vh;
}

我的逻辑是,当每个图像占100%宽度时," .imgcontainer" Div幻灯片左右左左幻灯片:-100%,每个图像都应从右侧逐一升起,直到达到最后一个再次恢复到第一个图像。

它不起作用!

请帮助。

您的"主要"问题在此行中:

$('.imgcontainer').css("margin-left") == (-300 % )
                                       // ^^^^^^^^

在旁边,您只能使用字符串格式"-300%".css("margin-left") 将为您提供一个PX值,您无法与未计算的%进行比较。

另一个问题是设置为100%的幻灯片将是其容器的宽度,实际上可能更大(3个幻灯片300%(。

解决方案:

相反,我建议您使用像0,1,2, 0,1... etc一样的c计数器。
比计算Overflow-Wrapper width 和动画scrollLeft: width * counter(而不是-marginLeft(。

在父母上使用 display:flex,在子div元素上使用 min-width:100%;(而不是将图像放在这些divs中!(

$(".imgcontainer").each(function(){ // Now you can have multiple independent sliders!
  var $gal = $(this),
      $slides = $gal.children(), // get the slides
      tot = $slides.length, // number of slides
      c = 0; // the counter we mentioned
  (function anim() { // internal animation callback function
    var w = $gal.width();
    c = ++c % tot;   // increment or loop-back counter to 0 
    $gal.delay(2000).animate({scrollLeft: w*c }, 1000, anim); // anim callback !
  }()); // << START!
});
/*QuickReset*/ *{margin:0;box-sizing:border-box;font:14px/1.4 sans-serif;} html,body{height:100%;}
.imgcontainer{
  position:relative;
  height: 93%; /* or whatever you see fit */
  display: flex;
  overflow: hidden;
}
.imgcontainer > div {
  min-width: 100%;
  background: none 50% 50% / cover;
  /* Set background-image inline (see HTML) */
  /* Or use inner images like you did */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="imgcontainer">
  <div style="background-image:url(http://placehold.it/500x340/0bf);">
    Slide 1
  </div>
  <div style="background-image:url(http://placehold.it/500x340/f0b);">
    Slide 2
  </div>
  <div style="background-image:url(http://placehold.it/500x340/b0f);">
    Slide 3
  </div>
</div>

最新更新