学习使用JQuery动画

266 阅读2分钟

人生的第一篇博客 (^▽^) 这次主要记录我学习JQuery动画的代码,通过获取标签来控制标签内容的显示隐藏、改变大小颜色等

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>JQuery效果</title>
    <style>
      #animate1 {
        margin-top: 10px;
        margin-bottom: 10px;
        width: 100px;
        height: 100px;
        background: #4ae224;
        position: relative;
      }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
      // 也可以写作 $(function(){ ... })

      $(document).ready(function () {
        $('p').click(function () {
          $(this).hide()
        })

        // 注意“#”号键 id使用“#” class使用“.”
        $('#hide').click(function () {
          $('p').hide()
        })
        $('#show').click(function () {
          $('p').show()
        })

        // speed
        $('#hideWithSpeed').click(function () {
          $('p').hide(2000)
        })
        // speed and callback
        $('.hideWithSpeedAndCallback').click(function () {
          $('p').hide(2000, function () {
            alert('具有回调的Hide方法已完成!')
          })
        })
        // 缓动函数:linear匀速 swing变速
        $('.hideWithSMF').click(function () {
          $('p').hide(5000, 'linear', function () {
            alert('缓动函数的回调隐藏。')
          })
        })
        // toggle切换hide/show

        // 动画效果
        // 注意:想要改变元素位置,position需设为absolute,fixed或者relative
        $('#animate1').click(function () {
          $(this).animate({
            // 距离左边250px
            left: '250px',
            opacity: '0.5',
            // 使用“+=150px”会无限增大
            // 甚至可以设置为“show”、“hide”、“toggle”,会沿着相应方向变化
            height: '150px',
            width: '150px',
          })
        })

        // 多个动画逐一运行
        $('div').click(function () {
          var div = $('div')
          div.animate({ width: '300px', opacity: '0.4' }, 'slow')
          div.animate({ height: '300px', opacity: '0.8' }, 'slow')
          div.animate({ width: '100px', opacity: '0.4' }, 'slow')
          div.animate({ height: '100px', opacity: '0.8' }, 'slow')
          div.animate({ fontSize: '3em' })
          div.animate({ fontSize: '16px' })
        })

        // 停止动画stop()方法:多个动画逐一运行时只停止当前动画,可加参数true停止所有动画stop(true)
      })
    </script>
  </head>
  <body>
    <p>点我一下,我就不见了</p>
    <p>我也是</p>
    <p>我不会</p>
    <p>骗你的</p>

    <button id="hide">点我都消失</button>
    <button id="show">点我又出现了?</button>
    <button id="hideWithSpeed">点我慢慢消失</button>
    <button class="hideWithSpeedAndCallback">有回调函数的消失按钮</button>
    <button class="hideWithSMF">缓动函数的回调隐藏按钮</button>

    <div id="animate1">点我我会变化</div>
  </body>
</html>