jquery .hover .animation используется для переключения между стопкой изображений, размещенных по z-index - PullRequest
2 голосов
/ 25 сентября 2010

Часть A

У меня есть следующее:

<div class="graphic fadehover" class="last">                
<img src="graphic5test image" alt="" class="a" />
<img src="graphic5-2test image" alt="" class="b" />
</div>  

с приложением css

.fadehover {display: block; height: 162px; margin: 70px 45px 0 0; position:relative;       width: 292px; z-index: 100; }
img.a {position: absolute; left: 0; top: 0; z-index: 10;}
img.b {position: absolute; left: 0; top: 0;}

и этот скрипт

$(document).ready(function(){
$("img.a").hover(
function() {
$(this).stop().animate({"opacity": "0"}, "slow");
},
function() {
$(this).stop().animate({"opacity": "1"}, "slow");
});

});

Затем я хотел бы повторно использовать сценарий для следующего:

<div class="animation" class="fadehover">

    <img src="/sun-low image" alt="sun rising" class=""/>
    <img src="/sun-hi image" alt="sun rising" class=""/>        
    <img src="/sun-hi image" alt="sun rising" class=""/>        
</div>

с приложенным css:

.animation {position: absolute; left: 675px; top: 10px; z-index: 25; } /*positions     sunrise and hills */

.hills{position: absolute; left: 340px; z-index: 50; }

img.e {position: absolute; left: 0; top: 0; z-index: 10;}
img.f {position: absolute; left: 0; top: 0; z-index:2; }

Я знаю, что ссылки на изображения выше неправильны, но, поскольку я новичок, стекопоток не позволит мне публиковать их без изменений.

Я хотел бы повторно использовать сценарий или его вариант, чтобы иметь возможность постепенно исчезать между тремя изображениями, расположенными по z-index (восходящего солнца), но не знаю, как получить дубликат версии сценария. нацеливаться на новые классы img.

Кто-нибудь может указать мне правильное направление для этого?

Спасибо.

1 Ответ

1 голос
/ 25 сентября 2010

Я не совсем понял, чего вы хотели, поэтому я сделал и то, и другое.

Если блок fadehover также имеет класс animation, он будет циклически проходить через все изображения внутри каждые 1,5 секунды, пока вы наводите курсор на блок. Без класса animation изображение просто изменится на следующий.

Я надеюсь, что все комментарии достаточно ясны, чтобы вы могли понять, что я делал в сценарии. О, и вот демонстрация всего этого .

$(document).ready(function(){

 // make first image in each block the current image & hide the rest
 $(".fadehover").each(function(){
  $(this).find("img:first").addClass("current");
  $(this).find("img:not(:first)").hide();
 });

 // display next image
 var timer,
  nextImg = function(el) {
   // fadeout current image
   var curImg = el.find('img.current')
    .removeClass('current')
    .stop(true, true).fadeOut('slow');
   // find next image; if no next image exist, reset to the first one
   curImg = (curImg.next().length) ? curImg.next() :  curImg.parent().find('img:first');
   // fadein current (next) image
   curImg
    .addClass('current')
    .fadeIn('slow');
  };

 // cycle through each image on hover
 $(".fadehover").hover(function(){
   var el = $(this);

   // if the fadehover has the animation class, then cycle through the images while hovering
   if (el.is('.animation')) {
    timer = setInterval(function(){ nextImg(el); }, 1500);
   }
   // no animation, just show the next image on hover
   nextImg(el);

  }, function(){
   var el = $(this);

   // on mouseout, stop animation, or do nothing
   if (el.is('.animation')) {
    clearInterval(timer);
   }
   // fadeIn, just in case the clearInterval breaks the animation
   el.find('.current').stop(true, true).fadeIn('slow');

  });

});

Обновление ( новое демо )

Теперь, когда я понимаю, что вам нужно, попробуйте этот код:

$(document).ready(function(){

 // make first image in each block the current image & hide the rest
 $(".fadehover").each(function(){
  $(this).find("img:first").addClass("current");
  $(this).find("img:not(:first)").hide();
 });

 // display next image
 var timer,
  nextImg = function(el) {
   // fadeout current image
   var curImg = el.find('img.current')
   // find next image; if no next image exist, add "done" class
   if (curImg.next().length) {
    // fadein current (next) image
    curImg
     .removeClass('current')
     .stop(true, true).fadeOut('slow')
     .next()
     .addClass('current')
     .fadeIn('slow');
   } else {
    el.addClass('done');
   }

  };

 // cycle through each image on hover
 $(".fadehover").hover(function(){
   var el = $(this);
   // if the element has the "done" class, then stop
   if (!el.is('done')) {
    timer = setInterval(function(){ nextImg(el); }, 2000);
   }
  }, function(){
   var el = $(this);
   if (el.is('done')) { return; }
   // on mouseout, stop animation
   clearInterval(timer);
   // fadeIn, just in case the clearInterval breaks the animation
   el.find('.current').stop(true, true).fadeIn('slow');
  });

});
...