简体   繁体   中英

Change Image On Hover Javascript

I have done my research and looked at tons of things, but none of them are working for me. This is my code at the moment. The original image displays fine, but nothing happens when I hover.

Javascript (In <head> )

<script>
    function onHover()
    {
        $("#news").attr('src', 'img/newsHover.png');
    }

    function offHover()
    {
        $("#news").attr('src', 'img/news.png');
    }
</script>

HTML

<img id="news" onmouseover="onHover();" onmouseout="offHover();" height="100px" width="100px" src="img/news.png"></a>

一个纯Java脚本答案,不需要任何外部函数或jquery

<img id="news" onmouseover="this.src='img/newsHover.png'" onmouseout="this.src='img/news.png'" height="100px" width="100px" src="img/news.png"> 

There may be a good reason for what you're doing, but are you sure you need to use JavaScript?

If you're not doing anything fancy then it would probably be better to use the CSS hover selector: http://www.w3schools.com/cssref/sel_hover.asp

this is very easy example, not animation:

HTML:

<img src='https://cdn2.iconfinder.com/data/icons/crystalproject/128x128/apps/clean.png'>

use jQuery:

$(document).ready(function(){
    $('img').hover(
        function(){$(this).attr("src","https://cdn2.iconfinder.com/data/icons/crystalproject/128x128/apps/exit.png")},
        function(){$(this).attr("src","https://cdn2.iconfinder.com/data/icons/crystalproject/128x128/apps/clean.png")}
    );
});

Example Not Animation


And this is example with animation:

HTML:

<img src='https://cdn2.iconfinder.com/data/icons/crystalproject/128x128/apps/clean.png' class='clean' >
<img src='https://cdn2.iconfinder.com/data/icons/crystalproject/128x128/apps/exit.png' class='exit' >

CSS:

img{
    position:absolute;
    top:0;
    left:0;
}

use jQuery:

$(document).ready(function(){

    $(".exit").hide();

    $(".clean").hover(function(){
        $(".clean").fadeOut();
        $(".exit").fadeIn();
    });    

    $(".clean").mouseleave(function(){
        $(".exit").fadeOut();
        $(".clean").fadeIn();
    });    

});

Example With Animation

So you can use only this example:

<img 
    src='https://cdn2.iconfinder.com/data/icons/crystalproject/128x128/apps/clean.png' 
    onmouseover="this.src='https://cdn2.iconfinder.com/data/icons/crystalproject/128x128/apps/exit.png'"
    onmouseout="this.src='https://cdn2.iconfinder.com/data/icons/crystalproject/128x128/apps/clean.png'"
    height="100px"
    width="100px"
    id="news"
>

EXAMPLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM