程序员
讲互联网的故事

Jquery实现让你的图片抖动起来

用jquery实现你的图片在鼠标移入时可以出现抖动的效果,以下是页面中调用的效果,给的示例为让所有图片都有这个抖动效果,你可以用jquery选择器自己设置要应用的目标图片。

<script type="text/javascript" src="https://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="./jquery.imgShake.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
        $(function()
        {
            $("img").each(function(k, img)
            {
                new JumpObj(img, 10);
                $(img).hover(function() { this.parentNode.parentNode.className = "hover" });
            });
        }); 
 </script>

以下代码粘贴后保存为:jquery.imgShake.js文件,随便你放到哪里,调用的时候路径要正确。

function JumpObj(elem, range, startFunc, endFunc) {
        //图片鼠标移上去的动画效果
        var curMax = range = range || 6;
       startFunc = startFunc || function(){};
        endFunc = endFunc || function(){};
        var drct = 0;
        var step = 1;
 
        init();
 
        function init() { elem.style.position = 'relative';active() }
        function active() { elem.onmouseover = function(e) {if(!drct)jump()} }
        function deactive() { elem.onmouseover = null }
 
        function jump() {
             var t = parseInt(elem.style.top);
            if (!drct) motionStart();
            else {
                var nextTop = t - step * drct;
                if (nextTop >= -curMax && nextTop <= 0) elem.style.top = nextTop + 'px';
                else if(nextTop < -curMax) drct = -1;
               else {
                    var nextMax = curMax / 2;
                    if (nextMax < 1) {motionOver();return;}
                    curMax = nextMax;
                    drct = 1;
                }
            }
            setTimeout(function(){jump()}, 200 / (curMax+3) + drct * 3);
         }
        function motionStart() {
            startFunc.apply(this);
            elem.style.top='0';
            drct = 1;
        }
          function motionOver() {
            endFunc.apply(this);
            curMax = range;
            drct = 0;
            elem.style.top = '0';
        }
 
        this.jump = jump;
        this.active = active;
        this.deactive = deactive;
}
赞(0) 打赏一下

评论 抢沙发

觉得文章有用就打赏一下博客作者

支付宝扫一扫打赏

微信扫一扫打赏