jQuery image hover effect

前端 未结 2 1600
佛祖请我去吃肉
佛祖请我去吃肉 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:52

    Overall I think this is what you're looking for:

    $.fn.sexyImageHover = function() { 
        var p = this, // parent
            i = this.children('img'); // image
    
        i.load(function(){
            // get image and parent width/height info
            var pw = p.width(),
                ph = p.height(),
                w = i.width(),
                h = i.height();
    
            // check if the image is actually larger than the parent
            if (w > pw || h > ph) {
                var w_offset = w - pw,
                    h_offset = h - ph;
    
                // center the image in the view by default
                i.css({ 'margin-top':(h_offset / 2) * -1, 'margin-left':(w_offset / 2) * -1 });
    
                p.mousemove(function(e){
                    var new_x = 0 - w_offset * e.offsetX / w,
                        new_y = 0 - h_offset * e.offsetY / h;
    
                    i.css({ 'margin-top':new_y, 'margin-left':new_x });
                });
            }
        });
    }
    

    You can test it here.

    Notable changes:

    • new_x and new_y should be divided by the images height/width, not the container's height/width, which is wider.
    • this is already a jQuery object in a $.fn.plugin function, no need to wrap it.
      • i and p were also jQuery objects, no need to keep wrapping them
    • no need to bind mousemove on mouseenter (which rebinds) the mousemove will only occur when you're inside anyway.

提交回复
热议问题