Ho alcune immagini e le loro immagini di rollover. Usando jQuery, voglio mostrare/nascondere l'immagine di rollover quando avviene l'evento onmousemove/onmouseout. Tutti i nomi delle mie immagini seguono lo stesso schema, come questo:
Immagine originale: Image.gif
.
Immagine Rollover: Imageover.gif
Voglio inserire e rimuovere la "over" porzione di origine dell'immagine nell'evento onmouseover e onmouseout, rispettivamente.
Come posso farlo usando jQuery?
Per impostare su pronto:
$(function() {
$("img")
.mouseover(function() {
var src = $(this).attr("src").match(/[^\.]+/) + "over.gif";
$(this).attr("src", src);
})
.mouseout(function() {
var src = $(this).attr("src").replace("over.gif", ".gif");
$(this).attr("src", src);
});
});
Per quelli che usano fonti di immagini url:
$(function() {
$("img")
.mouseover(function() {
var src = $(this).attr("src");
var regex = /_normal.svg/gi;
src = this.src.replace(regex,'_rollover.svg');
$(this).attr("src", src);
})
.mouseout(function() {
var src = $(this).attr("src");
var regex = /_rollover.svg/gi;
src = this.src.replace(regex,'_normal.svg');
$(this).attr("src", src);
});
});
So che stai chiedendo di usare jQuery, ma puoi ottenere lo stesso effetto nei browser che hanno JavaScript disattivato usando i CSS:
#element {
width: 100px; /* width of image */
height: 200px; /* height of image */
background-image: url(/path/to/image.jpg);
}
#element:hover {
background-image: url(/path/to/other_image.jpg);
}
C'è una descrizione più lunga qui
Ancora meglio, però, è usare gli sprite: simple-css-image-rollover
$('img.over').each(function(){
var t=$(this);
var src1= t.attr('src'); // initial src
var newSrc = src1.substring(0, src1.lastIndexOf('.'));; // let's get file name without extension
t.hover(function(){
$(this).attr('src', newSrc+ '-over.' + /[^.]+$/.exec(src1)); //last part is for extension
}, function(){
$(this).attr('src', newSrc + '.' + /[^.]+$/.exec(src1)); //removing '-over' from the name
});
});
Potresti voler cambiare la classe delle immagini dalla prima riga. Se hai bisogno di più classi di immagini (o di un percorso diverso) puoi usare
$('img.over, #container img, img.anotherOver').each(function(){
e così via.
Dovrebbe funzionare, non l'ho testato :)