2017-03-31 3 views
-1

J'essaie de créer une image survolée en fonction de la largeur et de la hauteur du navigateur. Voici le code actuel:Image de survol réactif

'<a href="google.com"><img src="http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_still_zpskfsuzshi.jpg" onmouseover="this.src='http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_zpsekucjvgf.gif'" onmouseout="this.src='http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_still_zpskfsuzshi.jpg'" /></a>' 

Des idées?

+0

Bienvenue sur stackoverflow.com! Nous faisons de notre mieux pour répondre aux questions des gens quand ils sont bien pensés et montrent des preuves de recherche et montrent le code. Veuillez lire la documentation suivante http://stackoverflow.com/help/how-to-ask, – Sethmr

Répondre

1

En général, vous pouvez faire quelque chose comme ceci:

<a href="google.com"><img id="myImage" src="http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_still_zpskfsuzshi.jpg" onmouseover="this.src='http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_zpsekucjvgf.gif'" onmouseout="this.src='http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_still_zpskfsuzshi.jpg'" /></a> 
<script> 
    var w = window.innerWidth; 
    document.getElementById("myImage").width = w; 
</script> 

Ce ajusteriez la largeur de l'image à la largeur intérieure de la fenêtre du navigateur. Si vous souhaitez ajuster en fonction de la hauteur, utilisez plutôt la propriété window.innerHeight. Vous pouvez écrire un peu de logique si vous voulez ajuster votre image par le plus petit des deux par rapport à votre image.

Ou, si vous voulez le faire en ligne:

<a href="google.com"><img src="http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_still_zpskfsuzshi.jpg" onmouseover="this.src='http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_zpsekucjvgf.gif'" onmouseout="this.src='http://i1146.photobucket.com/albums/o535/DanielleStateAuto/360_vid_033017_A_still_zpskfsuzshi.jpg'" width="window.innerWidth"/></a> 

fonctionnerait aussi, mais il serait difficile d'ajouter une logique supplémentaire à elle.

1

Une meilleure pratique moderne à ceci serait CSS non-JS/pure. Il existe quelques méthodes pour y parvenir, voici une:

<a href="#"><div class="myimg"></div></a> 

.myimg { 
    width:80%; 
    height:200px; 
    background: url(https://s-media-cache-ak0.pinimg.com/736x/bc/4e/38/bc4e386f24997b6f8c4c1f8ce96a7cef.jpg); 
    background-size: 100% 100%; 
    background-repeat: no-repeat; 
} 
.myimg:hover { 
    background: url(http://img00.deviantart.net/4ec1/i/2013/017/5/b/blue_eyed_huskey_by_ashleysmithphoto-d5rsvt2.jpg); 
    background-size: 100% 100%; 
    background-repeat: no-repeat; 
} 

Live Demo. Évidemment, vous devez configurer les propriétés CSS ci-dessus selon votre préférence/projet.