Javascript 使用 jQuery 在 pageLoad() 上隐藏元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5985208/
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-23 19:45:47  来源:igfitidea点击:

Hiding an element on pageLoad() with jQuery

javascriptjquerycss

提问by Sean Thoman

If I hide some elements on page_load using jquery, the elements flicker for a split second when the page posts and then disappear:

如果我使用 jquery 在 page_load 上隐藏了一些元素,当页面发布时这些元素会闪烁一秒钟然后消失:

  function pageLoad() {

        $('#panelOne').hide();
        $('#panelTwo').hide();

Is there a way to prevent the flickering?

有没有办法防止闪烁?

I don't want to set the elements css to visibility: hidden, because then calling the jquery .show() method later on doesn't seem to show the element.

我不想将元素 css 设置为可见性:隐藏,因为稍后调用 jquery .show() 方法似乎没有显示元素。

采纳答案by lonesomeday

Setting visibility: hiddendoesn't work, but display: nonedoes. See jsFiddle.

设置visibility: hidden不起作用,但display: none确实如此。参见 jsFiddle。

You could do this on the DOMReady event, but it would be cleaner to do it in CSS.

您可以在 DOMReady 事件上执行此操作,但在 CSS 中执行此操作会更清晰。

回答by Kevin Ennis

$.show()doesn't work on elements set to visibility: hidden. You need to use display: none. This will work out better for you than using jQuery to hide on DOM ready, and will absolutely guarantee you won't see flickering.

$.show()不适用于设置为 的元素visibility: hidden。您需要使用display: none. 这比使用 jQuery 在 DOM 就绪时隐藏更适合您,并且绝对保证您不会看到闪烁。

回答by Eli

Definitely use document ready as opposed to page load:

绝对使用文档就绪而不是页面加载:

$(function() {
    $('#panelOne, #panelTwo')
        .hide();
});

回答by Alxandr

Rather than hide on pageload, hide it on domready like so:

与其在页面加载时隐藏,不如像这样将其隐藏在 domready 上:

$(function() { ........ });

Replace the ...... with your 2 lines of hiding.

用你的 2 行隐藏替换......。

Domready runs when the dom-tree has been built, and much earlier than pageLoad. Pageload waits for images and stuff to run. (asuming that you have pageLoad as following: <html onload="pageLoad();">).

Domready 在构建 dom-tree 时运行,并且比 pageLoad 早得多。Pageload 等待图像和内容运行。(假设您的 pageLoad 如下:)<html onload="pageLoad();">