如何在jQuery中使用相对值创建动画

如何在jQuery中使用相对值创建动画

使用jQuery的animate()方法,我们可以向元素添加不同的CSS动画。这是jQuery中用于操作HTML元素和添加动画功能的强大方法之一。当我们改变animate()方法中的CSS样式时,动画效果就会产生。

要用一个相对值来改变一个元素的左或右或上或下,我们在CSS属性中使用+=value或-=value,这样它就把当前位置的值改变为相对于当前位置的相对增量或减量,并在CSS属性中给出值。

语法:使用animate()方法

$('selector').animate('direction'+='relative_value', other_parameters);

或者

$('selector').animate('direction'-='relative_value', other_parameters);

CSS()方法也可以通过使用以下语法直接使用。

语法:

$('selector').css('direction'+='relative_value', 'property':'value');

或者

$('selector').css('direction'-='relative_value', 'property':'value');

示例:

<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
     
    <!-- Including jQuery  -->
    <script src=
"https://code.jquery.com/jquery-3.6.0.min.js"
            integrity=
"sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" 
            crossorigin="anonymous">
   </script>
    <style>
        h2 {
            color: #006600;
        }
  
        button {
            color: white;
            background-color: #006600;
            width: 100px;
            height: 30px;
        }
  
        body {
            text-align: center;
        }
  
        div {
            border: 2px solid black;
            border-radius: 10px;
            margin: 10px;
            height: 100px;
            width: 100px;
            position: relative;
            left: 0;
            text-align: center;
        }
    </style>
</head>
  
<body>
  
    <h2>GeeksforGeeks</h2>
  
    <button id="btn-left"> Move Left</button>
    <button id="btn-right"> Move Right</button>
    <button id="btn-top"> Move Top</button>
    <button id="btn-bottom"> Move Bottom</button>
  
  
    <div id="GFG_IMAGE">
  
        <!-- Image added using img tag with src attribute -->
        <img src=
"https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg" 
         height='100px' width='100px'>
        <img>
    </div>
  
    <script>
        ('#btn-right').click(function () {
            ('div').animate({ 'left': '+=100px' });
        });
        ('#btn-left').click(function () {
            ('div').animate({ 'left': '-=100px' }, "fast");
        });
        ('#btn-top').click(function () {
            ('div').animate({ 'top': '-=100px' }, "fast");
        });
        ('#btn-bottom').click(function () {
            ('div').animate({ 'top': '+=100px' }, "fast");
        });
    </script>
  
</body>
  
</html>

输出:

如何在jQuery中使用相对值创建动画?

animate

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程