jQuery image hover effect

前端 未结 2 1607
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-10 03:57

I\'m trying to achieve this effect with jQuery.

I wrote some of the code, but it\'s buggy (move to the bottom-right corder and you\'ll see).
check it out

Bas

2条回答
  •  滥情空心
    2021-02-10 04:53

    Nick Craver beat me to an answer by about 10 minutes, but this is my code for this, using background-image to position the image instead of an actual image.

    var img = $('#outer'),
        imgWidth = 1600,
        imgHeight = 1200,
        eleWidth = img.width(),
        eleHeight = img.height(),
        offsetX = img.offset().left,
        offsetY = img.offset().top,
        moveRatioX = imgWidth / eleWidth - 1,
        moveRatioY = imgHeight / eleHeight - 1;
    
    
    img.mousemove(function(e){
        var x = imgWidth - ((e.pageX - offsetX) * moveRatioX),
            y = imgHeight - ((e.pageY - offsetY) * moveRatioY);
        this.style.backgroundPosition =  x + 'px ' + y + 'px';
    });
    

    The huge amount of variables are there because the mousemove event handler has to be as efficient as possible. It's slightly more restrictive, because you need to know the dimensions, but I think the code can be easily altered to work with imgs for which the size can be calculated easily.

    A simple demo of this: http://www.jsfiddle.net/yijiang/fq2te/1/

提交回复
热议问题