代码改变世界

Jquery实现百度的鼠标移入图片抖动的特效

2011-04-25 12:23  音乐让我说  阅读(878)  评论(0编辑  收藏  举报

代码能说明一切:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>实现百度的鼠标移入图片抖动的特效</title>
    <script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
    <script src="js/jquery.imgShake.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        $(function()
        {
            $("#ul img").each(function(k, img)
            {
                new JumpObj(img, 10);
                $(img).hover(function() { this.parentNode.parentNode.className = "hover" });
            });
        }); 
    </script>
</head>
<body>
	<ul id="ul" style="border:1px solid red;">
    	<li><img src="images/002.jpg" alt="效果很酷吧!"/></li>
    </ul>
</body>
</html>

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

谢谢浏览!