Jump to content

Dois slides com a mesma função mas tamanhos diferentes


terramoto
 Share

Recommended Posts

Tenho numa página dois slides de imagens com tamanhos diferentes e este código que queria adaptar aos dois, infelizmente quando troco o id por uma class e uso o slider as imagens repetem-se, presumo que haja conflito entre os dois.

jQuery(document).ready(function ($) {
 var slideCount = $('#slider1 ul li').length;
 var slideWidth = $('#slider1 ul li').width();
 var slideHeight = $('#slider1 ul li').height();
 var sliderUlWidth = slideCount * slideWidth;

 $('#slider1').css({ width: slideWidth, height: slideHeight });
 $('#slider1 ul').css({ width: sliderUlWidth, marginLeft: - slideWidth });

 $('#slider1 ul li:last-child').prependTo('#slider1 ul');
 $(window).resize(function(){
var slideCount = $('#slider1 ul li').length;
var slideWidth = $('#slider1 ul li').width();
var slideHeight = $('#slider1 ul li').height();
var sliderUlWidth = slideCount * slideWidth;

$('#slider1').css({ width: slideWidth, height: slideHeight });

$('#slider1 ul').css({ width: sliderUlWidth, marginLeft: - slideWidth });

$('#slider1 ul li:last-child').prependTo('#slider1 ul');
 });
 function moveLeft() {
	 $('#slider1 ul').animate({
		 left: + slideWidth
	 }, 200, function () {
		 $('#slider1 ul li:last-child').prependTo('#slider1 ul');
		 $('#slider1 ul').css('left', '');
	 });
 };
 function moveRight() {
	 $('#slider1 ul').animate({
		 left: - slideWidth
	 }, 200, function () {
		 $('#slider1 ul li:first-child').appendTo('#slider ul');
		 $('#slider1 ul').css('left', '');
	 });
 };
 $('a.control_prev').click(function () {
	 moveLeft();
 });
 $('a.control_next').click(function () {
	 moveRight();
 });
});

A great truth is a truth whose opposite is also a great truth.

Link to comment
Share on other sites

https://jsfiddle.net/Lskh1mey/2/

Já consegui, mas já agora, há alguma maneira mais prática(menos feia) de fazer isto?

jQuery(document).ready(function($){
$.each(['#slider1','#slider2'],function(index, slider){
	var slideCount = $(slider+' ul li').length;
	var slideWidth = $(slider+' ul li').width();
	var slideHeight = $(slider+' ul li').height();
	var sliderUlWidth = slideCount * slideWidth;

	$(slider).css({ width: slideWidth, height: slideHeight });
	$(slider+' ul').css({ width: sliderUlWidth, marginLeft: - slideWidth });
	$(slider+' ul li:last-child').prependTo(slider+' ul');

	function moveLeft() {
		$(slider+' ul').animate({
			left: + slideWidth
			}, 200, function () {
				$(slider+' ul li:last-child').prependTo(slider+' ul');
				$(slider+' ul').css('left', '');
		});
	}

	function moveRight() {
		$(slider+' ul').animate({
  			 left: - slideWidth
  			 }, 200, function () {
  			 $(slider+' ul li:first-child').appendTo(slider+' ul');
  			 $(slider+' ul').css('left', '');
  		 });
	}
	if(slider=='#slider1'){
		setInterval(function () {
	   	 moveRight();
		}, 3000);
	}
	$(slider+' a.control_prev').click(function () {
		moveLeft();
	});

	$(slider+' a.control_next').click(function () {
		moveRight();
	});
  });
  $(window).resize(function(){
   $.each(['#slider1','#slider2'],function(index, slider){
	   var slideCount = $(slider+' ul li').length;
	   var slideWidth = $(slider+' ul li').width();
	   var slideHeight = $(slider+' ul li').height();
	   var sliderUlWidth = slideCount * slideWidth;

	   $(slider).css({ width: slideWidth, height: slideHeight });
	   $(slider+' ul').css({ width: sliderUlWidth, marginLeft: - slideWidth });
	   $(slider+' ul li:last-child').prependTo(slider+' ul');
   });
  });
});
Edited by terramoto

A great truth is a truth whose opposite is also a great truth.

Link to comment
Share on other sites

Há. Crias um plugin e reduzes o código drasticamente.

Estive aqui a brincar com o teu código e poderás fazer as adaptações que quiseres, mas já ficas com uma ideia. Dei a possibilidade de no teu plugin o utilizador (neste caso tu) poderes definir se é um slide automático ou não.

O código está um bocado arrojado e não gosto de ter que escrever a classe notactive, mas isso será um problema para tu resolveres caso interpretes isso como problemático. Também alterei um bocado o esquema da tua linha de pensamento, eu só mostro e escondo as li.

Para chamares o plugin:

$('#slider1').bslider({automatic: true});
$('#slider2').bslider({automatic: false});
$('.slider3').bslider({automatic: true}); // <-- podes utilizar Id's ou classes

(function ($) {

   $.fn.bslider = function(options)
   {
       var settings = $.extend({

           automatic: false,

       }, options);

       var ul                 = $(this).find('ul');
       var li                 = $(ul).find('li');
       var slideCount         = $(li).length;
       var slideWidth         = $(li).width();
       var slideHeight        = $(li).height();
       var sliderUlWidth      = slideCount * slideWidth;

       $(this).css({ width: slideWidth, height: slideHeight });

       if(settings.automatic == true)
       {
           setInterval(function()
           {
               moveRight();
           }, 3000);
       }

       function moveRight() {
           $(ul).animate({
               left: - slideWidth
           }, 200, function ()
           {

               var current = $(ul).find('li.active');
               var next    = $(li).eq(current.index() + 1);

               if(current.index() == slideCount - 1)
                   next = $(ul).find('li').first();

               reset();
               show($(next));
           });
       }

       function moveLeft() {
           $(ul).animate({
               left: + slideWidth
           }, 200, function ()
           {

               var current = $(ul).find('li.active');
               var next    = $(li).eq(current.index() - 1);

               if(current.index() == slideCount - 1)
                   next = $(ul).find('li').first();

               if(current.index() == 0)
                   next = $(ul).find('li').last();

               reset();
               show($(next));
           });
       }

       $(this).find('a.control_prev').click(function ()
       {
           moveLeft();
       });

       $(this).find('a.control_next').click(function ()
       {
           moveRight();
       });

       function reset()
       {
           $(ul).find('li.active').removeClass('active')
                                  .addClass('notactive');
       }

       function show(item)
       {
           item.removeClass('notactive')
               .addClass('active');

           $(ul).css('left', '');
       }

   };

}(jQuery));

Ver exemplo prático em JSFiddle.

Entretanto enquanto escrevia este tópico reparei num bug no processo manual quando se anda para trás caso seja o primeiro elemento..se não conseguires resolver apita. 👍

Edited by bioshock
Link to comment
Share on other sites

Eu primeiro queria fazer um pure css slider para evitar trabalhar com o jquery. Mas depois vi que era mais trabalho que o que queria e tentei arranjar o slider mais simples que havia em jquery porque não pesco nada, mas consegui perceber o código. Vou aproveitar que tenho o js do jquery na página e aplicá-lo no que puder. Não tinha conhecimento dos plugins, obrigado!

No código, o bug, como não tens necessidade de voltar ao primeiro a partir do ultimo posso comentar esse if para não ficar no loop? Era a isso que estavas-te a referir?

A great truth is a truth whose opposite is also a great truth.

Link to comment
Share on other sites

Não consegues fazer tudo em CSS sem que não tenhas problemas de incompatibilidade entre browsers. Tens de utilizar jQuery para criar as animações que pretendes e ser compatível.

Existem muitos sliders, o que eu fiz foi criar o teu próprio plugin/slider que podes melhorá-lo e distribuí-lo como bem entenderes.

O bug está correcto. Se estiveres na primeira posição li e clicares no botão para trás o que é que é suposto fazer? Ir para o último e até aqui tudo bem. Se estiveres na última posição e clicares novamente para trás para onde deve ir? Para a penúltima posição e assim por diante. O que acontece é que o código que fiz verifica se é a última posição e manda-o para a primeira..

if(current.index() == slideCount - 1)
  next = $(ul).find('li').first();

Aconselho-te a melhorar o código caso pretendas ter a possibilidade do slider ser manual.

Link to comment
Share on other sites

Tirei a class "notactive", adicionei de inicio a class "active" ao primeiro porque em manual se nenhum tiver a class e andar para trás há algumas imagens que repetem-se na primeira volta, mas na segunda volta e adiante já voltando ao normal. Pelo menos que eu tenha visto agora, não apresenta nenhum bug ou glitch. Não sei se haverá melhor maneira, mas pelos menos está melhor que as linhas de código que tinha anteriormente. Obrigado!

http://jsfiddle.net/g7v14v5d/2/

A great truth is a truth whose opposite is also a great truth.

Link to comment
Share on other sites

Epá, ando aqui as turras com isto, tira-me uma dúvida se faz favor. O JQuery ou mesmo javascript não é 100% fiável no que toca a actualizar o conteúdo? É só porque eu tenho estado a configurar a página para acompanhar o tamanho do browser, mas à medida que vou alterando o tamanho do browser algumas vezes acabo por ficar com o scroll na horizontal, faço inspect e por mais que altere o tamanho do browser o width e height dos slides não se alteram, faço um refresh e o slide adapta-se, volto a brincar com o browser tudo bem, passado um bocado já está lá o scroll outra vez. tirei esta linha

//$(this).css({ width: slideWidth, height: slideHeight });

do código e configurei o tamanho através do @media e aparenta estar resolvido, agora não sei se é problema do javascript em si ou se há alguma coisa que esteja a fazer mal.

A great truth is a truth whose opposite is also a great truth.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.