CSS

21 jul, 2011

Deslizamento de imagem automático com CSS & jQuery

Publicidade

Com
o lançamento do iPad e sua falta de suporte para Flash, surgiram muitos debates
(inglês) acerca do futuro do Flash (inglês).
Tendo isso em mente, acredito ser prudente criar widgets simples como deslizamento de imagem usando HTML/CSS/Javascript, e deixar mais aplicativos interativos
disponíveis para o Flash se necessário. O deslizamento de imagem baseado em HTML terá
seus benefícios com SEO e também enfraquecerá aqueles sem js.

View Demo

O Wireframe – HTML

Comece
com um div englobador chamado main_view, e duas seções aninhadas dentro dele
chamadas image_reel e paging. O image_reel terá as 
imagens deslizadas, e o paging terá os controles da página. Dê uma olhada na imagem abaixo:

<div class="main_view">
<div class="window">
<div class="image_reel">
<a href="#"><img src="reel_1.jpg" alt="" /></a>
<a href="#"><img src="reel_2.jpg" alt="" /></a>
<a href="#"><img src="reel_3.jpg" alt="" /></a>
<a href="#"><img src="reel_4.jpg" alt="" /></a>
</div>
</div>
<div class="paging">
<a href="#" rel="1">1</a>
<a href="#" rel="2">2</a>
<a href="#" rel="3">3</a>
<a href="#" rel="4">4</a>
</div>
</div>

Estilos – CSS

Dê uma
olhada nos comentários abaixo para uma explicação sobre os estilos.

/*--Main Container--*/
.main_view {
float: left;
position: relative;
}
/*--Window/Masking Styles--*/
.window {
height:286px; width: 790px;
overflow: hidden; /*--Hides anything outside of the set width/height--*/
position: relative;
}
.image_reel {
position: absolute;
top: 0; left: 0;
}
.image_reel img {float: left;}

/*--Paging Styles--*/
.paging {
position: absolute;
bottom: 40px; right: -7px;
width: 178px; height:47px;
z-index: 100; /*--Assures the paging stays on the top layer--*/
text-align: center;
line-height: 40px;
background: url(paging_bg2.png) no-repeat;
display: none; /*--Hidden by default, will be later shown with jQuery--*/
}
.paging a {
padding: 5px;
text-decoration: none;
color: #fff;
}
.paging a.active {
font-weight: bold;
background: #920000;
border: 1px solid #610000;
-moz-border-radius: 3px;
-khtml-border-radius: 3px;
-webkit-border-radius: 3px;
}
.paging a:hover {font-weight: bold;}

Passo 3 – Criando o jQuery

Se você não é familiarizado com  jQuery, vá até o site deles primeiro e
entenda como ele funciona superficialmente. Eu compartilhei alguns truques que aprendi pelo caminho, e você
pode vê-los também.


Passo inicial – Chame o arquivo jQuery

Você pode
escolher fazer o download do arquivo a partir do site do jQuery, ou você pode usar este aqui hospedado no Google.

<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>

Exatamente
depois da linha em que você chamou seu jQuery, comece uma nova tag
<script>  e inicie seu código
usando o evento $(document).ready. Isso permite que seu código jQuery seja executado no momento em que o DOM está
pronto para ser manipulado. O código que você escreverá nos próximos passos será colocado dentro do seguinte lugar.

$(document).ready(function() {
//Code goes here
});

Passo 4 – Trazendo à vida – jQuery

O próximo
script contém comentários explicando quais ações do jQuery estão sendo
executadas.


Criando o
Image Slider

Comece mostrando a página e ativando o primeiro link. Então calcularemos e
ajustaremos a largura do image_reel de acordo com quantos deslizamentos teremos.

//Show the paging and activate its first link
$(".paging").show();
$(".paging a:first").addClass("active");

//Get size of the image, how many images there are, then determin the size of the image reel.
var imageWidth = $(".window").width();
var imageSum = $(".image_reel img").size();
var imageReelWidth = imageWidth * imageSum;

//Adjust the image reel to its new size
$(".image_reel").css({'width' : imageReelWidth});

Criando a função Slider e o cronômetro

Primeiramente,
criamos a função para o evento slide através dele mesmo (rotate). Então criamos
outra função (rotateSwitch), que irá alternar e repetir aquele evento slide
(rotate).

//Paging  and Slider Function
rotate = function(){
var triggerID = $active.attr("rel") - 1; //Get number of times to slide
var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide

$(".paging a").removeClass('active'); //Remove all active class
$active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)

//Slider Animation
$(".image_reel").animate({
left: -image_reelPosition
}, 500 );

};

//Rotation and Timing Event
rotateSwitch = function(){
play = setInterval(function(){ //Set timer - this will repeat itself every 7 seconds
$active = $('.paging a.active').next(); //Move to the next paging
if ( $active.length === 0) { //If paging reaches the end...
$active = $('.paging a:first'); //go back to first
}
rotate(); //Trigger the paging and slider function
}, 7000); //Timer speed in milliseconds (7 seconds)
};

rotateSwitch(); //Run function on launch

Dê uma
olhada neste tutorial para uma explicação sobre como o
cronômetro (setInterval) funciona.


Eventos Hover e
Click

Se o usuário quiser ver o slide por um longo
período de tempo, iremos permitir que o deslizamento pare quando o mouse passar em
cima dele. Outra coisa a considerar é que devemos resetar o cronômetro cada vez
que a página é clicada. Isso irá prevenir mudanças inesperadas de deslizamentos e
garantir uma experiência mais suave.

//On Hover
$(".image_reel a").hover(function() {
clearInterval(play); //Stop the rotation
}, function() {
rotateSwitch(); //Resume rotation timer
});

//On Click
$(".paging a").click(function() {
$active = $(this); //Activate the clicked paging
//Reset Timer
clearInterval(play); //Stop the rotation
rotate(); //Trigger rotation immediately
rotateSwitch(); // Resume rotation timer
return false; //Prevent browser jump to link anchor
});

?

Texto original disponível
em http://www.sohtanaka.com/web-design/automatic-image-slider-w-css-jquery/