terramoto Posted April 27, 2015 at 06:53 PM Report Share #581969 Posted April 27, 2015 at 06:53 PM 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 More sharing options...
bioshock Posted April 27, 2015 at 09:55 PM Report Share #582000 Posted April 27, 2015 at 09:55 PM Coloca em JSFiddle para vermos o problema. Link to comment Share on other sites More sharing options...
terramoto Posted April 28, 2015 at 10:10 AM Author Report Share #582030 Posted April 28, 2015 at 10:10 AM (edited) 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 April 28, 2015 at 02:58 PM by terramoto A great truth is a truth whose opposite is also a great truth. Link to comment Share on other sites More sharing options...
bioshock Posted April 28, 2015 at 08:58 PM Report Share #582078 Posted April 28, 2015 at 08:58 PM (edited) 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 April 28, 2015 at 08:59 PM by bioshock Link to comment Share on other sites More sharing options...
terramoto Posted April 29, 2015 at 10:19 AM Author Report Share #582103 Posted April 29, 2015 at 10:19 AM 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 More sharing options...
bioshock Posted April 29, 2015 at 11:16 AM Report Share #582107 Posted April 29, 2015 at 11:16 AM 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 More sharing options...
terramoto Posted April 29, 2015 at 12:48 PM Author Report Share #582117 Posted April 29, 2015 at 12:48 PM 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 More sharing options...
bioshock Posted April 29, 2015 at 01:09 PM Report Share #582118 Posted April 29, 2015 at 01:09 PM Pronto porreiro. O porreiro de ser plugin é que o podes escalar adicionando-lhe outras funcionalidades como por exemplo controlar o delay de alteração do slide.. Link to comment Share on other sites More sharing options...
terramoto Posted April 30, 2015 at 12:34 PM Author Report Share #582191 Posted April 30, 2015 at 12:34 PM 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 More sharing options...
bioshock Posted April 30, 2015 at 01:06 PM Report Share #582194 Posted April 30, 2015 at 01:06 PM No que toca a redimensionamentos de conteúdo não é do lado do javascript que o deves fazer. Deves fazê-lo do lado dos estilos (CSS), através dos media como referiste. Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now