jquery鼠标悬浮元素时图片向上滚动的代码

图片高度超过DOM元素节点高度,且父元素添加了overflow:hidden;图片超过高度的部分不会显示,通过鼠标悬浮图片,图片向上滚动的方式显示被截取的部分。

HTML代码:

<div class="scroll">
	<img src="图片URL地址" alt="长图片"/>
</div>

CSS代码:

.scroll {padding-bottom:50%; overflow:hidden;}
.scroll img {display: block; position: absolute; left:0; top:0; width: 100%; height: auto;}

jQuery代码:

使用requestAnimationFrame
$(function(){
	var dom = $('.scroll');
	var domh = dom.innerHeight();
	var domimg = new Image();
	domimg.src = dom.find('img').attr('src');
	domimg.onload = function(){
	    var imgh = dom.find('img').height();
	    if(imgh > domh){
	        var diff = imgh - domh;
	        var scroll;
	        dom.mouseenter(function(){                    
	            var num = 0; 
	            ;(function imgscroll(){
	                scroll = requestAnimationFrame(imgscroll);
	                if(num < diff){
	                    dom.find('img').css('transform','translateY(-'+ num +'px)');
	                    num++;
	                }else{
	                    cancelAnimationFrame(scroll);
	                }
	            })();                    
	        }).mouseleave(function(){
	            dom.find('img').css('transform','translateY(0)');
	            cancelAnimationFrame(scroll);
	        })
	    }
	}
});
使用setInterval
$(function(){
	var dom = $('.scroll');
	var domh = dom.innerHeight();
	var domimg = new Image();
	domimg.src = dom.find('img').attr('src');
	domimg.onload = function(){
	    var imgh = dom.find('img').height();
        if(imgh > domh){
            var diff = imgh - domh;
            var scroll;
            dom.mouseenter(function(){
                var num = 0;  
                scroll = setInterval(function(){
                    if(num < diff){
                        dom.find('img').css('transform','translateY(-'+ num +'px)');
                        num++;
                    }
                },10);
            }).mouseleave(function(){
                dom.find('img').css('transform','translateY(0)');
                clearInterval(scroll);
            })
        }
    }
});

如果浏览器不支持requestAnimationFrame则使用setInterval