前端入门(自留)——jquery自定义动画(简单)

130 阅读1分钟

相关知识

$(selector).animate({params},[speed],[fn]);

  • params(必选):动画形成的css属性
    • 使用DOM名称设置,即采用驼峰命名法,如 marginLeft
    • 属性值可以直接设置,也可以进行计算,如 width: '+=100px'
  • speed:动画效果时长(slow、normal、fast、毫秒数)
  • fn:动画完成后的回调函数

效果

  • 右漂变大:图片向右移动,宽高均变大
  • 图像下移:仅位置向下移动
  • 图片显示与隐藏:第一次图片向上收起并变透明;第二次图片向下展开并显示
  • 系列动画:图片依次向下拉长并变淡、向右拉宽、向上收缩并变得不透明、向左收缩

animate.gif

注意事项

  • 当同一元素包含多个动画时,会按先来后到的顺序,将新动画加入动画队列,每一轮的动画效果会在前一动画结束时的css参数下继续进行

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jquery-自定义动画</title>
    <script type="text/javascript" src="../js/jquery-3.7.1.js"></script>
    <style type="text/css">
        #showImg{
            background-color: #9b2;
            width: 150px;
            height: 200px;
            position: absolute;
            border: 10px solid #eee;
        }
        img{
            height: 100%;
            width: 100%;
            /* object-fit: contain; */
        }
    </style>
</head>
<body>
    <div>
        <input type="button" value="图像右漂变大" id="toRight">
        <input type="button" value="图像下移" id="toBottom">
        <input type="button" value="图像隐藏与显示" id="toHide">
        <input type="button" value="系列动画" id="toContinue">
    </div>
    <div id="showImg">
        <img src="../images/jquery-animate/1.jpg" alt="">
    </div>

    <script type="text/javascript">
        // 图像右漂变大
        $("#toRight").click(function(){
            $("#showImg").animate({
                left: '150px',
                width: '+=40px',
                height: '+=50px'
            },"fast");
        });
        // 图像下移
        $("#toBottom").click(function(){
            $("#showImg").animate({
                top: '+=50px'
            });
        });

        // 图像隐藏与显示
        $("#toHide").click(function(){
            $("#showImg").animate({
                height: 'toggle',
                opacity: 'toggle'
            });
        });

        // 系列动画
        $("#toContinue").click(function(){
            $("#showImg").animate({
                height: '+=100px',
                opacity: '0.4'
            },'slow');
            $("#showImg").animate({
                width: '+=80px',
                opacity: '0.4'
            },"slow");
            $("#showImg").animate({
                height: '200px',
                opacity: '1'
            },"slow");
            $("#showImg").animate({
                width: '150px',
                opacity: '1'
            },"slow");
        });
    </script>
</body>
</html>