Pergunta

I am trying to write a script, so that when someone hovers over an image, that same images changes to a different one, ie. I hover over up.png, and it changes to up_highlighted.png, when the mouse goes off the image it should change back.

However I can't seem to get it working despite all my attempts, here is the relevant code of what I have tried so far:

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. I do not wish to use sprites.

Foi útil?

Solução

Old School: 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;
    }
}

I'm sure the jquery is more pithy. Essentially you need a variable to hold the 'old' src URL, and mouseover and mouseout handlers to set the new URL and back it out.

Outras dicas

You don't have to wrap $(document).ready inside hover_up function. Note that I have removed onhover from HTML

Try

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);
    });
});

try this

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);
} 
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top