Py学习  »  Jquery

使用jquery和ajax淡入html页面的问题

Nono BNY • 4 年前 • 734 次点击  

作为一个在大学开始学习编码的初学者,我正在尝试完成我的第一个任务,包括使用css、html和js在故障时对网站进行编码(我们必须使用 $.getJSON() )中。

我在开始时遇到的问题是,我试图在加载的第一个html页面和第二个html页面之间创建一个平滑的淡入过渡,在这个页面上有一个按钮应该指向第二个页面我尝试遵循本教程:

https://www.superhi.com/video/simple-page-transitions-with-jquery-and-javascript (将“section”替换为“body”)但是要加载第二个页面,我需要刷新页面,它不能自己完成(即使淡入/淡出效果似乎起作用),尽管url确实发生了更改……有人能告诉我我在哪里搞砸了吗?

这是我的第一个html页面的主体

<body>
<div class="content">
<h1><a href="index2.html" id="index2go">Welcome to Greendale</a></h1>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
</script>
<script src="main.js"></script>
</body>

这是js页面

$("#index2go").on("click", function(event){
event.preventDefault()
const href = $(this).attr("href")
window.history.pushState(null, null, href)
$.ajax({
url: href,
success : function(data){ 
$("body").fadeOut(300, function(){ 
const newPage = $(data).filter("body").html()
$("body").html(newPage)
$("body").fadeIn(250)
})
}
})
})

非常感谢!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/48370
 
734 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Twisty
Reply   •   1 楼
Twisty    5 年前

我不确定你的项目范围,所以这可能超出了范围。使用fadein和fadeout,可以在转换结束时执行函数。有了ajax,就不完全一样了。这有点复杂,但这意味着即使AJAX正在处理请求,在返回数据之前可能还会执行更多的代码所以最好把所有的代码都包起来。

下面是一个建议的示例:

$(function() {
  function getContent(u, target, fn) {
    var newPage;
    console.log("GET " + u);
    var req = $.ajax({
      url: u,
      cache: false,
      dataType: "html",
      success: function(data) {
        console.log("SUCCESS ", data);
        newPage = $(data).find("body").childern();
        target.html(newPage);
        fn();
      },
      error: function(xhr, stat, error) {
        console.log("ERROR ", xhr, stat, error);
        newPage = $("<div>", {
          class: "error"
        }).html("Error " + stat + ": " + error);
        target.html(newPage);
        fn();
      }
    });
  }
  $("a").on("click", function(event) {
    event.preventDefault();
    var href = $(this).attr("href");
    window.history.pushState(null, null, href);
    $("body").fadeOut(300, function() {
      $("body").html("");
      getContent(href, $("body"), function() {
        $("body").fadeIn(250);
      });
    });
  });
});
<script src="http://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>

<div class="content">
  <h1><a href="index2.html" id="index2go">Welcome to Greendale</a></h1>
</div>