3

Estou a tentar a 'copiar' a mecânica do caroussel de boostrap (http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_carousel&stacked=h). Para a frente anda bem, não é a mesma mecanica do de bootstrap mas visualmente é, apesar de não ser a melhor forma pois vou adicionando infinitamente .item à div (agradeço sugestões para contornar isto), e para trás não funciona de todo.

var item_width = $('#slider-wrapper .item').width();
    var num_of_items = $('#slider-wrapper .item').length;
    var index_item_on = 0;
    
    $('#slider-wrapper').width(item_width * num_of_items);
    
    $('#next').on('click', function() {
        $('#slider-wrapper .item').eq(index_item_on).clone().appendTo('#slider-wrapper');
        $('#slider-wrapper').width($('#slider-wrapper').width() + item_width); // ajustar comprimento da div mãe
        $('#slider-wrapper').animate({
            'margin-left': '-=' +item_width+ 'px'
        },500);
        index_item_on++;
        if(index_item_on == 0) {
            index_item_on = 0;
        }
    });
    $('#prev').on('click', function() {
        $('#slider-wrapper').animate({
            'margin-left': '+=' +item_width+ 'px'
        }, 500);
        index_item_on--;
        if(index_item_on < 0) {
            $('#slider-wrapper .item').last().clone().prependTo('#slider-wrapper');
            index_item_on = num_of_items - 1;
        }
    });
    #slider-window {
        width: 150px;
        height:150px;
        border: 1px solid;
        position: relative;
        overflow:hidden;
    }
    #slider-wrapper .item {
        width: 150px;
        height: 150px;
        background-position: center center;
        background-size: cover;
        background-repeat: no-repeat;
        float: left;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="slider-window">
    <div id="slider-wrapper">
        <div class="item" data-item="1">HEYA 1</div>
        <div class="item" data-item="2">HEYA 2</div>
        <div class="item" data-item="3">HEYA 3</div>
    </div>
</div>
<h2>
    <b id="prev">&#8592; </b>
    <b id="next">&#8594; </b>
</h2>

2
  • Usar o prepend e o append não seria mais fácil do que usar o insertBefore e After?
    – MoshMage
    18/07/2016 às 16:02
  • Editei, consegui resolver parte do problema, Obgado @MoshMage
    – Miguel
    18/07/2016 às 16:04

2 Respostas 2

1

Miguel, vou apenas vou compartilhar um trabalho meu, talvez lhe dê algumas ideias.

var carousel = document.querySelector(".carousel");
var images = [
  "http://www.w3schools.com/bootstrap/img_chania.jpg",
  "http://www.w3schools.com/bootstrap/img_chania2.jpg",
  "http://www.w3schools.com/bootstrap/img_flower.jpg",
  "http://www.w3schools.com/bootstrap/img_flower2.jpg"
];

(function (carousel, images) {
  /* script to plugin */
  
  var inner = document.createElement("div");
  inner.classList.add("inner");
  carousel.appendChild(inner);

  var menu = document.createElement("div");
  menu.classList.add("menu");
  carousel.appendChild(menu);

  var atual = 0;
  var text = "";
  text += ".inner { width: " + (100 * images.length) + "%; }";
  text += ".image { width: " + (100 / images.length) + "%; }";
  images.forEach(function (image, indice) {
    var position = ((100 / images.length) * indice) + "%";
    text += "\n\r.image-" + indice + " { background-image: url(\"" + image + "\"); }";
    text += "\n\r.active-" + indice + " .inner { transform: translateX(-" + position + "); }";
    text += "\n\r.active-" + indice + " .action.image-" + indice + " { margin: 0px 2px; width: 48px; height: 48px; }";

    var image = document.createElement("div");
    image.classList.add("image");
    image.classList.add("image-" + indice);
    inner.appendChild(image);

    var action = document.createElement("div");
    action.classList.add("action");
    action.classList.add("image-" + indice);
    menu.appendChild(action);

    action.addEventListener("click", function (event) {
      carousel.classList.remove("active-" + atual);
      atual = indice;
      carousel.classList.add("active-" + atual);
    });
  });
  carousel.classList.add("active-" + atual);

  var blob = new Blob([text], { type: 'text/css' });
  var link = document.createElement("link");
  link.rel = "stylesheet" 
  link.type = "text/css" 
  link.href = URL.createObjectURL(blob);
  document.head.appendChild(link);
})(carousel, images);
#carousel {
  width: 450px;
  height: 300px;
}

/* Estilo do Plugin */
.carousel {
  position: relative;  
  overflow: hidden;
}

.carousel .inner {
  position: relative;
  height: 100%;
  transition: all 0.5s linear;
}

.carousel .action {
  transition: all 0.5s linear;
} 

.carousel .menu {
  position: absolute;
  left: 50%;
  bottom: 5px;
  transform: translateX(-50%);
}

.carousel .image  {
  float: left;
  position: relative;
  height: 100%;
}

.carousel .action {
  float: left;
  width: 32px;
  height: 32px;
  background-size: cover;
  border-radius: 50%;
  border: 2px solid white;
  margin: 8px 2px;
  box-shadow: inset 0px 0px 10px white;
}
<div id="carousel" class="carousel">
</div>

1
  • Obgado Toby, não é bem o que eu quero mas parebéns, o efeito dos botões está engraçado
    – Miguel
    18/07/2016 às 17:45
0

Feito, fiz o seguinte:

var item_width = $('#slider-wrapper .item').width();
var num_of_items = $('#slider-wrapper .item').length;
var index_item_on = 0;

$('#slider-wrapper').width(item_width * num_of_items);

$('#slider-wrapper').prepend($('#slider-wrapper .item').last());
$('#slider-wrapper').css({'left' : -item_width});

$('#next').on('click', function() {
    if(!$('#slider-wrapper').is(':animated')) {
        var left_move = parseInt($('#slider-wrapper').css('left')) - item_width;
        $('#slider-wrapper').stop().animate({
            'left': left_move
        }, 300, function(){
                $('#slider-wrapper').append($('#slider-wrapper .item').first());
                $('#slider-wrapper').css({'left' : -item_width});
           });
    }
});

$('#prev').on('click', function() {
    if(!$('#slider-wrapper').is(':animated')) {
        var left_move = parseInt($('#slider-wrapper').css('left')) + item_width;
        $('#slider-wrapper').stop().animate({
            'left': left_move
        }, 300, function(){
                $('#slider-wrapper').prepend($('#slider-wrapper .item').last());
                $('#slider-wrapper').css({'left' : -item_width});
            });
    }
});
#slider-window {
    width: 140px;
    height:140px;
    border: 1px solid;
    overflow:hidden;
}
#slider-wrapper {
    position: relative;
}
#slider-wrapper .item {
    width: 140px;
    height: 140px;
    background-position: center center;
    background-size: cover;
    background-repeat: no-repeat;
    float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="slider-window">
    <div id="slider-wrapper">
        <div class="item" data-item="1">HEYA 1</div>
        <div class="item" data-item="2">HEYA 2</div>
        <div class="item" data-item="3">HEYA 3</div>
    </div>
</div>
<h2>
    <b id="prev">&#8592; </b>
    <b id="next">&#8594; </b>
</h2>

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .