2011-09-20 2 views
1

У меня есть анимация, которая срабатывает при нажатии.jQuery анимация

У меня есть четыре изображения, и я хочу сделать больше по щелчку и отобразить текст.

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

здесь HTML-

<div id="nav" style="width: 980px; position: absolute; left: 100px; overflow: hidden" > 
<div class="item active"> 
    <img src="images/image1.png" width="148" height="190" /> 
    <div style="width:350px; position: absolute; left: 250px; bottom: 0px; z-index: 100"> 
     <h2 style="color:#009DD8">Title1</h2>  
     <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas turpis turpis, rutrum nec euismod ac, mattis eget felis</p> 
    </div> 
</div> 
<div class="item"> 
    <img src="images/image2.jpg" width="148" height="190" /> 
    <div style="width:350px; position: absolute; left: 250px; bottom: 0px; z-index: 100"> 
     <h2 style="color:#902272">Title2</h2> 
     <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas turpis turpis, rutrum nec euismod ac, mattis eget felis</p></div> 
</div> 
<div class="item"> 
    <img src="images/image3.png" width="148" height="190" /> 
    <div style="width:350px; position: absolute; left: -375px; bottom: 0px; z-index: 100"> 
     <h2 style="color:#68AA41">Title3</h2>  
     <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas turpis turpis, rutrum nec euismod ac, mattis eget felis</p> 
    </div> 
</div> 
<div class="item"> 
    <img src="images/image4.png" width="148" height="190" /> 
    <div style="width:350px; position: absolute; left: -395px; bottom: 0px; z-index: 100"> 
     <h2 style="color:#F5B21D">Title4</h2> 
     <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas turpis turpis, rutrum nec euismod ac, mattis eget felis</p> 
    </div> 
</div> 

здесь является JQuery

$(document).ready(function() { 
    $("#nav div.active").animate({"width": 244,"height": 316}, 1500).addClass('active'); 
    $("#nav div.active").find('img').animate({"width": 244, "height": 316}, 1500); 
    $("#nav div.active").find('div').fadeIn(100); 

    $('#nav div').click(function(){   
     if($(this).hasClass('active')) 
     { 
      $(this).animate({"width": 148, "height": 190}, 1500).removeClass('active'); 
      $(this).find('img').animate({"width": 148, "height": 190}, 1500); 
      $(this).find('div').fadeOut(500); 
     } 
     else  
     { 
      $(this).animate({"width": 244,"height": 316}, 1500).addClass('active'); 
      $(this).find('img').animate({"width": 244, "height": 316}, 1500); 
      $(this).find('div').fadeIn(100); 
      $('.active').not(this).find('img').animate({"width": 148,"height": 190}, 1500); 
      $('.active').not(this).find('div').css({"display": "none"}); 
      $('.active').not(this).animate({"width": 148,"height": 190}, 1500).removeClass('active'); 
     } 
    }); 

});

Я попытался добавить .stop() в места, но это еще хуже. Есть идеи?

Мне нужны эти линии, чтобы стрелять в одно время, один изменяет размер изображения другого его контейнера div. если я fireone после другого, то он щурит

$(this).animate({"width": 244,"height": 316}, 1500).addClass('active'); 
$(this).find('img').animate({"width": 244, "height": 316}, 1500); 

$(this).animate({"width": 148, "height": 190}, 1500).removeClass('active'); 
$(this).find('img').animate({"width": 148, "height": 190}, 1500); 

я думаю, что я хочу сделать, это задержка функции нажмите, пока текущая анимация не будет завершена или, еще лучше, если другой будет нажата во время анимации, чтобы отменить его и возврат в нормальное состояние перед обжигом функции OnClick

кредита Николаса C.

я также попытался

$('#nav div').click(function(){ 

    if(!$('#nav div').is(':animated')) 
    { 
     if($(this).hasClass('active')) 
     { 
      $(this).animate({"width": 148, "height": 190}, 1500).removeClass('active'); 
      $(this).find('img').animate({"width": 148, "height": 190}, 1500); 
      $(this).find('div').fadeOut(500).stop(true, true); 
     } 
     else  
     { 
      $(this).animate({"width": 244,"height": 316}, 1500).addClass('active'); 
      $(this).find('img').animate({"width": 244, "height": 316}, 1500); 
      $(this).find('div').fadeIn(100).stop(true, true); 

      $('.active').not($(this)).find('img').animate({"width": 148,"height": 190}, 1500); 
      $('.active').not($(this)).find('div').fadeOut(500).stop(true, true); 
      $('.active').not($(this)).animate({"width": 148,"height": 190}, 1500).removeClass('active'); 
     } 
    } 
}); 

работает, но не V чень дружественным к пользователю, если они щелкают и оно не реагирует

+0

вопросы о jquery not css! – Adam

+0

Ну, чем Адам ... ваш вопрос (даже без скрипки), для меня, выглядит так. Вот почему я спросил о некоторых CSS. http://jsfiddle.net/roXon/wzkwN/ –

+0

Думаю, я должен начать использовать скрипку. вы можете увидеть эту проблему, если вы нажмете на прямоугольники перед завершением анимации. – Adam

ответ

0

Попробуйте используя .animate() функции обратного вызова -

$('.active').not(this).animate({"width": 148,"height": 190}, 1500, function() { 
    $(this).removeClass('active'); 
}); 
0

Попробуйте использовать полную функцию обратного вызова для другой анимации, как следует:

$("first_animation").animate({"width": 244,"height": 316}, 1500, 'swing',function(){ 
    $("second_animation").animate({"width": 244,"height": 316}, 1500, 'swing',function(){ 
    $("third_animation").animate({"width": 244,"height": 316}, 1500, 'swing'); 
    }) 
}) 

выше код будет аминировать все три div first_animation, second_animation и third_animation. по одному.

+0

- это не функция обратного вызова, запущенная по завершении первого? Я хочу, чтобы эти линии срабатывали одновременно $ (this) .animate ({"width": 244, "height": 316}, 1500) .addClass ('active'); $ (this) .find ('img'). Animate ({"width": 244, "height": 316}, 1500); – Adam

1

Это может быть не лучшее решение, но попробуйте и сообщите мне, если это то, что вы намереваетесь делать, зная, что я заменил ваши изображения значками 24x24 и принял окончательное поведение, которое вы ожидаете.

отдельный файл CSS, содержащий:

div.item{ 
    height: auto; 
    border: 1px solid red; 
} 
img.icon{ 
    display: inline; 
    position: relative; 
    top: 0px; 
} 

div.content{ 
    display: inline-block; 
    position: relative; 
    top: 0px; 
} 

div.inactive div.content{ 
    display: none; 
} 
div.inactive{ 
    width: 16px; 
    height: 16px; 
} 

HTML часть:

<div id="nav" style="width: 980px; position: absolute; left: 100px; overflow: hidden" > 
<div class="item inactive"> 
    <img class="icon" src="images/image1.png" width="16" height="16" /> 
    <div class="content"> 
     <h2 style="color:#009DD8">Title1</h2>  
     <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas turpis turpis, rutrum nec euismod ac, mattis eget felis</p> 
    </div> 
</div> 
<div class="item inactive"> 
    <img class="icon" src="images/image2.png" width="16" height="16" /> 
    <div class="content"> 
     <h2 style="color:#902272">Title2</h2> 
     <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas turpis turpis, rutrum nec euismod ac, mattis eget felis</p></div> 
</div> 
<div class="item inactive"> 
    <img class="icon" src="images/image3.png" width="16" height="16" /> 
    <div class="content"> 
     <h2 style="color:#68AA41">Title3</h2>  
     <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas turpis turpis, rutrum nec euismod ac, mattis eget felis</p> 
    </div> 
</div> 
<div class="item inactive"> 
    <img class="icon" src="images/image4.png" width="16" height="16" /> 
    <div class="content"> 
     <h2 style="color:#F5B21D">Title4</h2> 
     <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas turpis turpis, rutrum nec euismod ac, mattis eget felis</p> 
    </div> 
</div> 

Javascript часть:

$(document).ready(function() { 
    $('#nav div.item').click(function(){ 
     var myItems = $('.item'); 
     var pendingAnimation = false; 
     for(var i = 0; i < myItems.length; i++) 
     { 
      if($(myItems[i]).is(':animated')){ 
       pendingAnimation = true; 
       break; 
      } 
     } 
     if(!pendingAnimation){ 
      //extend the item 
      $(this).animate({"width": 700, "height": 150}, 1500); 
      //make it an active item 
      $(this).addClass('active'); 
      //grow the icon 
      $(this).find('img').animate({"width": 24, "height": 24}, 1500); 
      //make the content of the item fade in 
      $(this).find('div.content').fadeIn(100); 

      //Fading out the content of all the other active elements 
      $('.item').not($(this)).find('div.content').fadeOut(500); 
      //Shrinking all the other active icons 
      $('.item').not($(this)).find('img').animate({"width": 16,"height": 16}, 1500); 
      //Shrinking all the other active items 
      $('.item').not($(this)).animate({"width": 16,"height": 16}, 1500); 
      //making all the other items as "inactive" 
      $('.item.active').removeClass('active').addClass('inactive'); 
     } 
    });   
}); 

Эффект: при нажатии на иконе, он расширяет щелкнул DIV ,item, делает его активным и оживляет любой другой «активный» элемент с обратной анимацией.

+0

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

+0

Это более или менее то, что он делает уже, ваш код имеет ту же проблему. если вы нажмете элемент 1 и до завершения анимации щелкните пункт item2, item3 и item 4, у вас будет вся анимация, которая не то, что я хочу. Я пытаюсь найти способ отложить/отменить/остановить текущую анимацию до того, как функция щелчка будет вызвана – Adam

+0

Хорошо, поэтому я не понял, в чем была его проблема. Я пробовал его код, и он явно ничего не отображал правильно, поэтому я предположил. –

Смежные вопросы