jquery按时间间隔替换图像

jQueryReplacing images at time intervals

本文关键字:替换 图像 时间 jquery      更新时间:2023-09-26

我想在我的标志上添加圣诞灯。我本来打算在flash中做这个,但我想放弃flash,所以我决定用jQuery试试。

快速谷歌搜索返回本教程。这让我走上了正确的道路。问题是我不想让图像淡入淡出所以我替换了

$active.fadeOut(function() $next.fadeIn().addClass('active');

,active.show美元(next.show美元()()函数.addClass("活跃的");

的问题是,它只旋转通过图像一次,然后停止。我尝试使用hide代替,但它做了一个奇怪的放大效果。

简而言之,我有4个图像,我试图通过使用以下代码循环它们:

    function swapImages(){
  var $active = $('#myGallery .active');
  var $next = ($('#myGallery .active').next().length > 0) ? $('#myGallery .active').next() : $('#myGallery img:first');
  $active.show(function(){
  $active.removeClass('active');
  $next.show().addClass('active');
  });
}
  $(document).ready(function(){
      setInterval('swapImages()', 1000);
})
Html:

  <div id="myGallery">
      <img src="br_xmas_1.png" class="active" />
      <img src="br_xmas_2.png" />
      <img src="br_xmas_3.png" />
     <img src="br_xmas_4.png" />
</div>

查看部分工作的完整代码在这里或不工作jsfiddle

试试这个;

function swapImages() {
    var $current = $('#myGallery img:visible');
    var $next = $current.next();
    if($next.length === 0) {
        $next = $('#myGallery img:first');
    }
    $current.hide();
    $next.show();
}
$(document).ready(function() {
    // Run our swapImages() function every 0.5 secs
    setInterval(swapImages, 500);
});

工作示例

奖励(随机更改)

function swapImages() {
    var random = Math.floor(Math.random()*3),
        $current = $('#myGallery img:visible');
    $current.hide();
    if($current.index() == random) {
        random = ++random % 4;
    }
    $('#myGallery img').eq(random).show();
}
$(document).ready(function() {
    // Run our swapImages() function every 0.5 secs
    setInterval(swapImages, 500);
});

啊,已经回答了。

试试这个

你已经使用了show()函数,它为元素添加了display:block样式。因此,在一次运行之后,所有的图像都同时显示,最后一个图像位于其他图像的顶部,因此显示一个。