繁体   English   中英

JavaScript悬停时更改图像

[英]JavaScript changing image when hovering

我正在尝试编写一个脚本,以便当有人将鼠标悬停在一张图片上时,同一张图片会更改为另一张图片。 我将鼠标悬停在up.png上,它更改为up_highlighted.png,当鼠标离开图像时,它应该变回原来的状态。

但是,尽管我进行了所有尝试,但似乎无法使它正常工作,这是到目前为止我尝试过的相关代码:

print "<img src=\"/images/up.png\" class=\"thumbsbtn1\" style=\"position:absolute;top:60px;left:1px;width:28px;\" onhover=\"hover_up()\" onclick=\"increase_rating()\">";
function hover_up(){
$(document).ready(function() {
    var oldSrc = $('.thumbsbtn1').attr('src');

    $('.thumbsbtn1').hover(function() {
        //on hover of your element

        $('.thumbsbtn1').attr('src','/images/up_hover.png');
    }, function() {
        //when the cursor leaves your element

        $('.thumbsbtn1').attr('src', oldSrc);
    });
});
}

PS。 我不想使用精灵。

您不必将$(document).ready包装在hover_up函数中。 请注意,我已经从HTML中删除了onhover

尝试

print "<img src=\"/images/up.png\" class=\"thumbsbtn1\" style=\"position:absolute;top:60px;left:1px;width:28px;\" onclick=\"increase_rating()\">";


$(document).ready(function() {
    var oldSrc;
    $(document).on('hover', '.thumbsbtn1', function () {
        oldSrc = $('.thumbsbtn1').attr('src');
        $('.thumbsbtn1').attr('src','/images/up_hover.png');
    }, function () {
        $('.thumbsbtn1').attr('src', oldSrc);
    });
});

老派: http : //jsfiddle.net/PAGUp/

var elem = document.getElementById('targetImg');
var oldSrc;
elem.onmouseover = function() {
    oldSrc = elem.src;
    elem.src = 'http://www.eclipse-developers.com/images/up_hover.png';
}

elem.onmouseout = function() {
    if(typeof oldSrc !== 'undefined') {
        elem.src = oldSrc;
    }
}

我敢肯定,jQuery更精简了。 本质上,您需要一个变量来保存“旧” src URL,并使用mouseover和mouseout处理程序来设置新URL并将其撤消。

尝试这个

print "<img src=\"/images/up.png\" class=\"thumbsbtn1\" style=\"position:absolute;top:60px;left:1px;width:28px;\" onhover=\"hover_up(this)\" onclick=\"increase_rating()\" onmouseout=\"hover_out(this)\">";


var oldSrc;
function hover_up(e){
oldSrc = $('.thumbsbtn1').attr('src');
$('.thumbsbtn1').attr('src','/images/up_hover.png');
}  
function hover_out(e){
$('.thumbsbtn1').attr('src',oldSrc);
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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