如何在渲染之前使用jQuery隐藏元素?

问题描述 投票:44回答:12

我想生成具有可以有条件地显示/隐藏的区域(div,spans)的html布局。默认情况下隐藏这些区域。

如果我在document.ready上使用jquery调用.hide()方法,这些区域可能会闪烁(浏览器呈现部分加载的文档)。所以我在html布局中应用“display:none”样式。

我想知道避免眨眼的最佳做法是什么,因为应用“display:none”打破了封装规则 - 我知道jquery用hide / show做什么并使用它。如果jquery的隐藏/显示实现有一天会改变,我会让整个网站变得不可行。

先感谢您

jquery html hidden
12个回答
3
投票

设置元素的初始显示属性绝对没有错,特别是如果将其封装在css类中。


0
投票

这是我的建议。它利用this solution创建一个新的CSS规则。主要的事情是:如果JS可用,将创建隐藏某些html的CSS类,否则不会。这发生在主要内容(应该最初隐藏的html部分)得到处理之前!

<html>
<head>
    <style>
        /* This class gets overwritten if JS is enabled. If a css file (bootstrap, ...) 
        gets loaded with such a class this would be also overwritten. This solution does 
        not require the class. It is here just to show that it has no effect 
        if JS is activated.*/
        .hidden {
            display: block;
            background: red;
        }
    </style>
    <script>
        // this is copied from the linked stackoverflow reply:
        function setStyle(cssText) {
            var sheet  = document.createElement('style');
            sheet.type = 'text/css';
            /* Optional */
            window.customSheet = sheet;
            (document.head || document.getElementsByTagName('head')[0]).appendChild(sheet);
            return (setStyle = function (cssText, node) {
                if (!node || node.parentNode !== sheet)
                    return sheet.appendChild(document.createTextNode(cssText));
                node.nodeValue = cssText;
                return node;
            })(cssText);
        }

        // And now: This class only gets defined if JS is enabled. Otherwise 
        // it will not be created/overwritten.
        setStyle('.hidden { display: none; }');

        // Attention: Now that the class is defined it could be overwritten 
        // in other CSS declarations (in style tags or with loaded CSS files).
    </script>
</head>
<body>

    <button>Show/Hide</button>

    <div class="">before</div>
    <div class="my-element hidden">
        Content that should be initially hidden if possible.
        You may want to multiply this div by some thousands
        so that you see the effect. With and without JS enabled.
    </div>
    <div class="">after</div>

    <script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
    <script>
        // Here is some 'normal' JS code. Very likely loaded as a JS file:
        $('button').click(function () {
            $('.my-element').toggleClass('hidden');
            // or setting display directly: 
            //   $('.my-element').toggle() 
            // but well, having class hidden though it is not 
            // hidden makes is not so nice...
        })
    </script>

</body>
</html>

有点复杂,但我认为这是一个合适的解决方案。优点是可以防止闪烁,并且如果未启用JS,则可以使用闪烁。它不需要jQuery。


0
投票

经过一段时间的思考,我已经有了以下解决方案的想法。与我的other solution相比,我已将其缩减为必要部分(并使用this通过JS添加类):

<html>
<head>
    <style>
        /* This could be also part of an css file: */
        .container-with-hidden-elements .element {
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <script>
            document.getElementsByClassName('container')[0]
                    .className += ' container-with-hidden-elements';
        </script>

        <div class="element">Content that should be initially hidden if possible.</div>
    </div>
</body>
</html>

脚本标记立即执行,并将一个类添加到容器中。在这个容器中有一些现在隐藏的嵌套元素,因为容器有特殊的类,并且有一个CSS规则现在有效。

同样,这发生在剩余的html被处理之前(防止闪烁)。而且,如果JS被禁用,默认情况下所有元素都是明显的 - 可以称为Progressive enhancement

不确定这是否适用于所有浏览器。但IMO将是简单而简洁的解决方案。


0
投票

有很多答案,你可以使用show()方法和代码显示或隐藏条件。这是示例代码show_hide when rendering is complete

  <div id="banner-message">
  <p id="hello">Hello World!!!!!</p>
  <input id="statusconf" value="" type="checkbox">Show hello world text when i click this check box
  <button>Change color</button>
</div>

    // find elements
var banner = $("#banner-message")
var button = $("button")

// handle click and add class
button.on("click", function(){
  banner.addClass("alt")
})

//Set this up as part of document ready if you wish
//$(document).ready(function(e) {

    $("#statusconf").show(function(e) {
            if ($("#statusconf").is(':checked') === false) {
                $('#hello').hide();
            } else {
        $("#hello").show();
      }
  });

    $("#statusconf").on("click", function(e) {
    if ($("#statusconf").is(':checked') === false) {
                $('#hello').hide();
            } else {
        $("#hello").show();
      }
  });

//});

33
投票

@安德鲁,

我知道答案已被接受,但使用display: none;对于没有Javascript的用户来说将是一场噩梦。

使用内联Javascript,您可以隐藏元素,而不会闪烁。没有Javascript的用户仍然可以看到它。

考虑一些在页面加载时应该隐藏的div。

<head>
    <script type="text/javascript" src="jQuery.js"></script>
</head>
<body>
    <div id="hide-me">
        ... some content ...
    </div>
    <script type="text/javascript">
        $("#hide-me").hide();
    </script>

    <div id="hide-me-too">
        ... some content ...
    </div>
    <script type="text/javascript">
        $("#hide-me-too").hide();
    </script>
</body>

内联Javascript将在呈现元素时立即运行,从而将其隐藏在用户之外。


5
投票

我同意BorisGuéry的观点,即它不是过度工程,而是标准的最佳实践。我会采用与Boris稍微不同的方式,首先在html中添加一个no-js类,然后用JavaScript删除它。

这样您就不会等待文档准备好隐藏内容,而且没有任何JavaScript,您仍然可以看到内容。假设用户没有JavaScript更符合渐进增强的理念。

例如:

<html class="no-js">
<body>
<div id="foo"></div>
</body>
</html>

我的css:

#foo {
    display: none;
}
html.no-js #foo {
    display: block;
}

和javascript

$(document).ready(
   function()
   {
     $('html').removeClass('no-js');
   }
);

*********或每个案例***********

例如:

<div class="no-js" id="foo">foobar and stuff</div>

CSS:

.no-js {
  display:none;
}
#foo {
  display: block;
}
#foo.no-js {
  display: none;
}

JS:

$(document).ready(function(){
  // remove the class from any element that has it.
  $('.no-js').removeClass('no-js');
});

3
投票

我通常在我的元素中设置一个.js类,以便在启用javascript时设置适当的属性。

然后,我可以根据javascript是否存在来设置CSS。

例如:

<html class="js">
<body>
<div id="foo"></div>
</body>
</html>

我的css:

html.js #foo
{
    display: none;
}

和javascript

$(document).ready(
   function()
   {
     $(html).addClass('js');
   }
);

3
投票

我也在努力解决这个问题,特别是在IE中,我发现这非常有用:http://robertnyman.com/2008/05/13/how-to-hide-and-show-initial-content-depending-on-whether-javascript-support-is-available/


3
投票

为什么不这样做?:

// Hide HTML element ASAP
$('html').hide();

// DOM-ready function
$(function () {
   // Do stuff with the DOM, if needed
   // ...

   // Show HTML element
   $('html').show();
}

它似乎工作正常!

问候。


1
投票

你可以在CSS类中应用“display:none”。

因为浏览器必须读取一些HTML代码才能让JavaScript找到Element。当浏览器读取您的HTML时,您必须将元素标记为隐藏。

您如何在JavaScript中插入HTML,并且可以在呈现之前调用hide。


0
投票

我总是会使用Modernizr.js http://modernizr.com/来处理这个问题。

使用Mondernizr,您的页面的HTML标记中会添加“js”或“no-js”类。

从这里,只有当html标签具有js类时,才能隐藏元素。

Modernizr非常适合其他许多应用程序,如果您之前没有使用它,请继续阅读:http://modernizr.com/docs/


0
投票

我一直在做的是创建一个空div。如果需要显示该组件中的某些数据,我会使用$ .ajax()异步加载数据(即html)。

不需要额外的lib。

© www.soinside.com 2019 - 2024. All rights reserved.