如何用jQuery在两秒内追加一个元素

如何用jQuery在两秒内追加一个元素

给出一个HTML元素,任务是在JQuery的帮助下使用fadeIn效果在几秒钟后在文档中追加一个元素。

步骤:

  • 选择目标元素,以追加该元素。
  • 使用appendTo()或append()方法中的一个来追加该元素。

例子1:在这个例子中,将 <div>元素用append()方法附加到该<body>元素上的。

<!DOCTYPE HTML> 
<html> 
  
<head> 
    <title> 
        How to append an element in
        two seconds using jQuery ?
    </title>
      
    <style>
        #div {
            background: green;
            height: 100px;
            width: 200px;
            margin: 0 auto;
            color: white;
            display: none;
        }
    </style>
      
    <script src = 
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
    </script>
</head> 
  
<body style = "text-align:center;"> 
      
    <h1 style = "color:green;" > 
        GeeksForGeeks 
    </h1>
      
    <p id = "GFG_UP" style =
        "font-size: 19px; font-weight: bold;">
    </p>
      
    <div id = "div">Div Element.</div>
      
    <button onClick = "GFG_Fun()">
        click here
    </button>
      
    <p id = "GFG_DOWN" style =
        "color: green; font-size: 24px; font-weight: bold;">
    </p>
      
    <script>
        ('#GFG_UP').text("Click on button to fade in element.");
          
        function GFG_Fun() {
            ('#div').append("body").fadeIn(2000);
            $('#GFG_DOWN').text("Div fades in after 2 second."); 
        }
    </script> 
</body> 
  
</html>

输出:

  • 在点击按钮之前。
    如何用jQuery在两秒内追加一个元素?
  • 点击该按钮后。
    如何用jQuery在两秒内追加一个元素?

例子2:在这个例子中,使用appendTo()方法<div>元素被附加到<p>元素。

<!DOCTYPE HTML> 
<html> 
  
<head> 
    <title> 
        How to append an element in
        two seconds using jQuery ?
    </title>
      
    <style>
        #div {
            background: green;
            height: 100px;
            width: 200px;
            margin: 0 auto;
            color: white;
            display: none;
        }
    </style>
      
    <script src = 
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
    </script>
</head> 
  
<body style = "text-align:center;"> 
      
    <h1 style = "color:green;"> 
        GeeksForGeeks 
    </h1>
      
    <p id = "GFG_UP" style =
        "font-size: 19px; font-weight: bold;">
    </p>
      
    <div id = "div">Div Element.</div>
      
    <button onClick = "GFG_Fun()">
        click here
    </button>
      
    <p id = "GFG_DOWN" style = 
        "color: green; font-size: 24px; font-weight: bold;">
    </p>
      
    <script>
        ('#GFG_UP').text("Click on button to fade in element.");
      
        function GFG_Fun() {
            ('#div').appendTo("p").fadeIn(2000);
            $('#GFG_DOWN').text("Div fades in after 2 second."); 
        }
    </script> 
</body> 
  
</html>

输出:

  • 在点击按钮之前。
    如何用jQuery在两秒内追加一个元素?
  • 点击该按钮后。
    如何用jQuery在两秒内追加一个元素?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程