鼠标悬停不工作

mouseover not working?

本文关键字:工作 悬停 鼠标      更新时间:2023-09-26

Web开发专业的学生,正在尝试一个简单的javascript鼠标悬停。这个代码不起作用,有什么建议吗?编辑:这已经被编辑,现在正试图使用悬停。

<DOCTYPE! html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title id="title"> Hybris Studios </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<script>
$(document).ready(function() {  
// Rollover image
var homeBlack = new Image();
homeBlack.src = "http://hybrisstudios.com/Images/HomeBlack.png";
var oldSrc = $('.homeRed').attr('src');
$('.homeRed').hover(function() {
    $(this).attr('src', homeBlack.src);
},
function() 
{
    $(this).attr('src', oldSrc);    
}); // end hover        
}); // end ready
</script>
</head>
<body>
<!-- Image Divs -->
<div class="homeRed">
<img src="Images/HomeRed.png"/>
</div>
</body>
</html>
<!-- CSS -->
<style type="text/css">
.homeRed {
    position : fixed;
    top  : 180px;
    left : 170px;
    }
</style>

您可以直接更改mouseover或mouseleave上的图像src,而无需创建Image对象。

Fiddle

HTML:

<img src="http://s25.postimg.org/e2wx0t4p7/chrome.png" />

jQuery:

$('img').mouseover(function() {
    $(this).attr('src', 'http://s25.postimg.org/46vu15yx7/tardis.jpg');
}).mouseleave(function() {
    $(this).attr('src', 'http://s25.postimg.org/e2wx0t4p7/chrome.png');
});

||----编辑----||

Fiddle

您的代码已修复。

HTML:

<div class="homeRed">
    <img src="http://s25.postimg.org/e2wx0t4p7/chrome.png" />
</div>

jQuery:

$(document).ready(function () {
    $('.homeRed').mouseover(function () {
        $(this).find('img').attr('src', "http://s25.postimg.org/46vu15yx7/tardis.jpg");
    });
});

CSS:

.homeRed {
    position : fixed;
    top : 180px;
    left : 170px;
}

您使用了错误的图像选择器。您选择的是div,而不是img。

$('.homeRed')

正确的是:

$('.homeRed>img')

整条线应该是:

$('.homeRed>img').hover(function() {

尝试使用这个

$(document).ready(function() {
    // Rollover image
    var homeBlack = new Image();
    homeBlack.src = "Images/HomeBlack.png";  //this is a shorthand for the actual src
    $('.homeRed').hover(function() {
        $(this).attr('src', homeBlack.src);
    }); // end mouseover        
}); // end ready

这个怎么样:

$(document).ready(function() {
    // Rollover image
    var homeBlack = new Image();
    homeBlack.src = "Images/HomeBlack.png";  //this is a shorthand for the actual src
    $('.homeRed').on('mouseover', function() {
         $(this).attr('src', homeBlack.src);
    }); // end mouseover        
});