使用 Jquery 使一个元素淡出,一个新元素淡入

Making one element fade out and a new element fade in with Jquery

本文关键字:元素 一个 新元素 淡入 淡出 使用 Jquery      更新时间:2023-09-26

我有一个页面,我会让它使用Jquery进行导航。当我单击一个链接时,我希望一个部分消失,而我通过要插入的 get 方法获得一个新部分。

我已经部分工作了,但是,fadeIn() 方法似乎不起作用,我 100% 确定我应该如何执行此任务。

这是我索引页的 HTML

<div class="mid_section">
        <div class="home_content container">
            <div class="step_second_row">   
                <ul>
                    <li>
                        <a href="about.php" id="about_link">Learn more</a>
                    </li>
                    <li>
                        something
                    </li>
                    <li>
                        something
                    </li>
                </ul>
            </div>
        </div>
    </div>

Jquery

$(document).ready(function(){
    $("#about_link").on("click", function( e ){
        $(".home_content").fadeToggle("slow", function() {
            $.get("about.php", function( response ) {
                var content = $(response).find(".about_content");
                $(".mid_section").fadeIn("slow").html(content);
            });
        });
        e.preventDefault();
    });
});

正在加载的节

<h1>About us!!!</h1>
<p>
    Lorem ipsum dolor sit amet
</p>

我真的很挣扎,谁能告诉我如何实现这种事情?或者我做错了什么,我也还在学习Jquery的过程中。

谢谢你的时间。

试试 rhis:

$(".mid_section").html(content).hide().fadeIn("slow");

先加载内容然后淡入淡出可能会解决您的问题。

首先执行 ajax 调用,这样当元素淡出时它可能会完成,然后使用返回的承诺来捕获响应并淡入另一个元素

$(document).ready(function(){
    $("#about_link").on("click", function( e ){
        e.preventDefault();
        var xhr = $.get("about.php");
        $(".home_content").fadeToggle("slow", function() {
            xhr.done(function(response) {
                var content = $(response).find(".about_content");
                $(".mid_section").hide().html(content).fadeIn("slow");
            });
        });
    });
});

请注意,您不会淡入和淡出相同的元素?

要使

fadeIn 正常工作,必须隐藏元素,在您的情况下,当fadeIn被称为元素时,该元素是可见的,因为您正在淡出home_content

而是在home_content上调用fadeOut

$(document).ready(function () {
    $("#about_link").on("click", function (e) {
        $(".mid_section").fadeToggle("slow", function () {
            $(this).load('about.php .about_content', function () {
                $(this).fadeIn("slow")
            })
        });
        e.preventDefault();
    });
});

还可以使用 .load() 加载远程内容

  $(document).ready(function(){
      $("#about_link").on("click", function( e ){
        $.get("about.php", function( response ) {
          $(".mid_section").fadeOut("slow", function() {

                var content = $(response).find(".about_content");
                $(".mid_section").html(content).fadeIn("slow");
            });
        });
        e.preventDefault();
    });
  });