Jquery простой поворот изображения в зависимости от ролловера - влево или вправо - как сделать это непрерывным? - PullRequest
0 голосов
/ 05 февраля 2020

Я учусь Jquery и у меня есть простой скрипт поворота изображения, который показывает три изображения и позволяет вам при наведении курсора мыши поместить одно изображение в центр и сместить остальные соответственно, в зависимости от того, находится мышь слева или справа , Я в порядке, как это работает справа, но не слева. Оба изображения просто всплывают внезапно, но справа это как-то работает лучше, и левый переход раздражает. Любые идеи?

И, во-вторых, что еще более важно, мне нужно сделать это вращение непрерывным. Как только изображения повернуты, и мышь уходит и снова входит в левое или правое изображение, мне нужно снова сделать поворот. Каков лучший способ go об этом? Я попытался создать классы .left .center и .right и переназначить их в конце каждой анимации, но это, похоже, не работает.

JS Скрипка - https://jsfiddle.net/unata/4km5cf0r/

<div class="featured_listings">
  <div id="carousel">


<div><img src="https://via.placeholder.com/200/808080/000000?text=roll over me"></div>
<div><img src="https://via.placeholder.com/200/0000CC/000000?Text=div2"></div>
<div><img src="https://via.placeholder.com/200/00CCCC/000000?text=roll over me"></div>

</div>
</div>

Jquery:

$('#carousel div:nth-child(2)').addClass('selected'); 
//put orange border around the selected item            


var div_widthtotal = 230; 
var ijustmoved=0; 
$("#carousel div:nth-child(1)").addClass("left"); 
$("#carousel div:nth-child(2)").addClass("center"); 
$("#carousel div:nth-child(3)").addClass("right"); 


$(".right").mouseenter(function() {
        $(this).addClass('selected'); 
        $(this).siblings().removeClass('selected'); 
    //this is to stop the hover effect from repeating
        if (ijustmoved ==0) {
        $("#carousel").animate({marginLeft: -div_widthtotal}, function(){
            $(".left").clone().insertAfter(".right"); 
            //don't move me anymore
            ijustmoved=1; 
        });         
        }
    });

    $(".left").mouseenter(function() {
        $(this).addClass('selected'); 
            $(this).siblings().removeClass('selected'); 
    if (ijustmoved ==0) {
        //on animation clone the left div 
        $("#carousel").animate({marginLeft: div_widthtotal}, function(){
            $(".right").clone().insertBefore(".left"); 
            $("#carousel").css('margin-left', 0);  
            //don't move me anymore
            ijustmoved=1; 
        });         
        }


    });

1 Ответ

1 голос
/ 06 февраля 2020

Это должно помочь куче. Это еще не идеально. Есть некоторые проблемы с переключением анимации поля в ноль в неподходящее время. Но это значительное улучшение.

Ключом к непрерывной анимации была повторная установка ролловера на ваших клонах после добавления их в DOM.

$('#carousel div:nth-child(2)').addClass('selected'); 
//put orange border around the selected item            

var div_widthtotal = 230; 
$("#carousel div:nth-child(1)").addClass("left"); 
$("#carousel div:nth-child(2)").addClass("center"); 
$("#carousel div:nth-child(3)").addClass("right"); 

function setupRight(el)
{
  el.unbind('mouseenter.roll').bind('mouseenter.roll', function() {
    el.addClass('selected'); 
    el.siblings().removeClass('selected');
    //on animation clone the left div and remove all the classes)
    $("#carousel").animate({marginLeft: -div_widthtotal}, function()
    {
      $("#carousel div:nth-child(1)").clone().insertAfter("#carousel div:nth-child(3)"); 
      $("#carousel").css('margin-left', 0);  
      setupRight($("#carousel div:nth-child(4)"));
      $("#carousel div:nth-child(1)").empty().remove();
      setupLeft($("#carousel div:nth-child(1)"));
      //don't move me anymore
      el.unbind('mouseenter.roll');
    });
  });
}

function setupLeft(el)
{
  el.mouseenter(function() {
    el.addClass('selected'); 
    el.siblings().removeClass('selected');
    //on animation clone the left div 
    $("#carousel").animate({marginLeft: div_widthtotal}, function(){
      $("#carousel div:nth-child(3)").clone().insertBefore("#carousel div:nth-child(1)"); 
      $("#carousel").css('margin-left', 0);  
      $("#carousel div:nth-child(4)").empty().remove();
      setupRight($("#carousel div:nth-child(3)"));
      setupLeft($("#carousel div:nth-child(1)"));
      //don't move me anymore
      el.unbind('mouseenter.roll');
    });
  });
}

setupRight($("#carousel div:nth-child(3)"));
setupLeft($("#carousel div:nth-child(1)"));

РЕДАКТИРОВАТЬ - 2020- 02-06

Я думаю, что теперь это то, что вам нужно. Оплата не требуется. Это было весело. Возможно, вам придется немного изменить его для реального сценария (в частности, селекторы jQuery, например, 'img', которые, безусловно, слишком широки), но, надеюсь, это укажет вас туда, где вам нужно go.

HTML

<div class="featured_listings">
  <div id="carousel">
    <div class="imgWrp">
      <img src="https://via.placeholder.com/200/808080/000000?text=One">
      <img src="https://via.placeholder.com/200/0000CC/000000?Text=Two">
      <img src="https://via.placeholder.com/200/00CCCC/000000?text=Three">
    </div>
  </div>
</div>

CSS

html, body {
  margin: 0;
  padding: 0;
}


.featured_listings {
  width: 70%;
  max-width: 940px; 
  margin: auto; 
  margin-top: 10%; 
  overflow: hidden; 
}

#carousel{
  display: inline-block;
  width: 100%;
  max-width: 100%;
  padding: 1em 0;
  margin: 0;
  overflow: hidden;
  white-space: nowrap;
}

.featured_listings img {
  max-width: 200px; 
  margin: 0 1em;

}

.imgWrp {
  display: inline-block;
}

.selected {
  -moz-transform: scale(1.08);
  -ms-transform: scale(1.08);
  -o-transform: scale(1.08);
  -webkit-transform: scale(1.08);
  border: 5px solid #e67e22;
  transform: scale(1.08);
  transition: all ease-in-out .3s;
}

JS

$(function() {
  //put orange border around the selected item
  $('#carousel .imgWrp img:nth-child(2)').addClass('selected');

  // Set margin amount
  var div_widthtotal = 230;

  // Find and create jQuery elements
  var carousel = $('#carousel');
  var imgWrp = $('.imgWrp');
  var newFirst = $('#carousel .imgWrp img:first-child').clone();
  var newSecond = $('#carousel .imgWrp img:nth-child(2)').clone();
  var newThird = $('#carousel .imgWrp img:last-child').clone();

    // This function places the images in the correct location
  function scrollToCenter(ms)
  {
    var img = carousel.find('img.selected');
    var desiredCenter = img[0].offsetLeft;
    var actualCenter = carousel.width() / 2;
    var lftScroll = desiredCenter - actualCenter;
    carousel.animate({
      scrollLeft: lftScroll
    }, ms);
  }

    // This is the on-mouse-enter function
  function onMouseenter(el)
  {
    if (el.index() == 1)
    {
        var newFirst = $('#carousel .imgWrp img:last-child');
      newFirst.css("margin-right", 0);
      newFirst.css("margin-left", -newFirst.width() + 'px');
      $('#carousel .imgWrp img:first-child').before(newFirst);
      el.addClass('selected');
      el.siblings().removeClass('selected');
      newFirst.animate({ 'marginLeft': '1em', 'marginRight': '1em' }, 400);
    }
    else if (el.index() == 3)
    {
      $('#carousel .imgWrp img:last-child').after($('#carousel .imgWrp img:first-child'));
      scrollToCenter(0);
      el.addClass('selected');
      el.siblings().removeClass('selected');
      scrollToCenter(400);
    }
  }

    // This is where all images will be bound to the mouse-enter function at one time
  function bindImgs()
  {
    $('img').each(function(i, img){
      var el = $(img);
      el.unbind('mouseenter.roll').bind('mouseenter.roll', function(e){
        // First, turn off mouse-enter functionality
        $('img').unbind('mouseenter.roll');
        // Next, run the process to move the images around
        onMouseenter(el);
      });
    });
  }

    // Make it so the user can re-activeate the mouse-enter functionality when they leave the scroller
  carousel.unbind('mouseleave.scroller').bind('mouseleave.scroller', function(e){
    bindImgs();
  });

    // Additional setup
  $('#carousel .imgWrp img:last-child').after(newFirst);
  $('#carousel .imgWrp img:last-child').after(newSecond);
  $('#carousel .imgWrp img:first-child').before(newThird);

  // Launch functionality
  scrollToCenter(0);
  bindImgs();
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...