在页面启动时使用 JQuery .load() 和 .hide() 和 .show()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13295396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:28:53  来源:igfitidea点击:

Using JQuery .load() with .hide() and .show() on page startup

jquery

提问by e-zero

I'm using the following code to show a divon page startup:

我正在使用以下代码来显示div页面启动:

$("#mydiv").hide().show("slow");

This will make the divappear with a slow animation on page startup (page load / refresh)

这将使div页面启动时出现缓慢的动画(页面加载/刷新)

However, if, on page startup (page load / refresh), I want to insert HTML from another file into this divbefore this animation starts I try to do this:

但是,如果在页面启动(页面加载/刷新)时,我想div在此动画开始之前将另一个文件中的 HTML 插入到此动画中,我会尝试执行以下操作:

$("#mydiv").load("myPage.html");
$("#mydiv").hide().show("slow");

When I do this, the animation no longer works on startup (page load / refresh). How can I load html from another file and still have the animation work on page startup (page load / refresh)?

当我这样做时,动画在启动时不再起作用(页面加载/刷新)。如何从另一个文件加载 html 并在页面启动(页面加载/刷新)时仍然有动画工作?

回答by Kev Price

$(document).ready(function(){  
  $('#mydiv').load('myPage.html', function() {
      $(this).show();
    });
});

in your css add

在你的 css 添加

#mydiv { 
   display: none; 
}

回答by Zoltan Toth

It is better to use CSS for initial hiding of your div

最好使用 CSS 来初始隐藏您的 div

#mydiv { display: none }

and then you can show it

然后你可以展示它

$("#mydiv").load("myPage.html", function() {
    $(this).show(600);
});

回答by Wouter J

I recommend to hide the page, load the content and then show the div. You can simply do using the second argument (complete) of .load(url[, data][, complete]):

我建议隐藏页面,加载内容,然后显示 div。您可以简单地使用第二个参数 ( complete) .load(url[, data][, complete])

$('#myDiv').load('...', function() {
    // gets executed when the content is loaded
    $(this).show('slow');
});

回答by Naftali aka Neal

Add the show part as a callback to the load:

将 show 部分作为回调添加到负载:

$("#mydiv").hide().load("myPage.html", function(){
    $(this).show('slow');
});

回答by e-zero

I have figured out a way.

我想出了一个办法。

You an do something like this using ajax:

你可以使用 ajax 做这样的事情:

$.ajax({
        url: "myPage.html",
        cache: false
    }).done(function (html) {
        $("#myDiv").append(html);
        $("#myDiv").hide().show("slow");
    });

This ensure the page is called before the animation begins!

这确保在动画开始之前调用页面!