如何在渲染之前使用 jQuery 隐藏元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2801032/
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
How to hide elements with jQuery before they get rendered?
提问by Andrew Florko
I want to generate html layout with areas (divs, spans) that can be shown/hidden conditionally. These areas are hidden by default.
我想生成带有可以有条件地显示/隐藏的区域(div、跨度)的 html 布局。默认情况下,这些区域是隐藏的。
If I call .hide() method with jquery on document.ready these areas may blink (browsers render partially loaded documents). So I apply "display: none" style in html layout.
如果我在 document.ready 上使用 jquery 调用 .hide() 方法,这些区域可能会闪烁(浏览器呈现部分加载的文档)。所以我在 html 布局中应用了“显示:无”样式。
I wonder what is the best practice to avoid blinking, because applying "display:none" breaks incapsulation rule - I know what jquery does with hide/show and use it. If jquery's hiding/showing implementation will change one day, I'll get the whole site unworkable.
我想知道避免闪烁的最佳做法是什么,因为应用“display:none”会破坏封装规则——我知道 jquery 对隐藏/显示做了什么并使用它。如果 jquery 的隐藏/显示实现有一天会改变,我会让整个站点无法运行。
Thank you in advance
先感谢您
采纳答案by James H
There's absolutely nothing wrong with setting an intial display property of an element, especially if you encapsulate it in a css class.
设置元素的初始显示属性绝对没有错,特别是如果您将其封装在 css 类中。
回答by Marko
@Andrew,
@安德鲁,
I know the answer has already been accepted, but using display: none;
will be a nightmare to users without Javascript.
我知道答案已经被接受,但是display: none;
对于没有 Javascript 的用户来说,使用将是一场噩梦。
Using inline Javascript, you can hide an element without it ever blinking. Users without Javascript will still be able to see it.
使用内联 Javascript,您可以隐藏一个元素而不让它闪烁。没有 Javascript 的用户仍然可以看到它。
Consider a few divs that should be hidden when the page loads.
考虑一些在页面加载时应该隐藏的 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>
The inline Javascript will run as soon as the element is rendered, thus hiding it from the user.
内联 Javascript 将在元素呈现后立即运行,从而对用户隐藏它。
回答by Ryan Ore
I agree with Boris Guéry, that it is not over-engineering, but rather, a standard best practice. I would go a slightly different way than Boris, by adding a no-js class to the html initially and then removing it with JavaScript.
我同意 Boris Guéry 的观点,这不是过度设计,而是标准的最佳实践。我会采用与 Boris 略有不同的方式,首先向 html 添加一个 no-js 类,然后使用 JavaScript 将其删除。
This way you're not waiting for the document to be ready to hide the content, and without any JavaScript you still see the content. Assuming the user has not JavaScript is more in line with the philosophy of progressive enhancement.
这样,您无需等待文档准备好隐藏内容,并且无需任何 JavaScript 您仍然可以看到内容。假设用户没有 JavaScript 更符合渐进增强的哲学。
ex:
前任:
<html class="no-js">
<body>
<div id="foo"></div>
</body>
</html>
my css :
我的CSS:
#foo {
display: none;
}
html.no-js #foo {
display: block;
}
and javascript
和 javascript
$(document).ready(
function()
{
$('html').removeClass('no-js');
}
);
********* OR on a per-case basis***********
********* 或以个案为基础************
ex:
前任:
<div class="no-js" id="foo">foobar and stuff</div>
css:
css:
.no-js {
display:none;
}
#foo {
display: block;
}
#foo.no-js {
display: none;
}
js:
js:
$(document).ready(function(){
// remove the class from any element that has it.
$('.no-js').removeClass('no-js');
});
回答by Boris Guéry
I usually set a .js class to my element to set the proper property when javascript is enabled.
我通常为我的元素设置一个 .js 类,以便在启用 javascript 时设置正确的属性。
I then can set the CSS depending on if javascript is present or not.
然后我可以根据javascript是否存在来设置CSS。
ex:
前任:
<html class="js">
<body>
<div id="foo"></div>
</body>
</html>
my css :
我的CSS:
html.js #foo
{
display: none;
}
and javascript
和 javascript
$(document).ready(
function()
{
$(html).addClass('js');
}
);
回答by Andy
Why not do just this?:
为什么不这样做?:
// Hide HTML element ASAP
$('html').hide();
// DOM-ready function
$(function () {
// Do stuff with the DOM, if needed
// ...
// Show HTML element
$('html').show();
}
It seems to work fine!
它似乎工作正常!
Regards.
问候。
回答by tester testers
I struggled with this too, especially in IE, and I found this very helpful: http://robertnyman.com/2008/05/13/how-to-hide-and-show-initial-content-depending-on-whether-javascript-support-is-available/
我也为此苦苦挣扎,尤其是在 IE 中,我发现这非常有帮助:http: //robertnyman.com/2008/05/13/how-to-hide-and-show-initial-content-depending-on-whether -javascript-support-is-available/
回答by robsch
This is my suggestion. It utilizes this solutionto createa new CSS rule. The main thing: a CSS class that hides some html will be created if JS is available, otherwise not. And this happens beforethe main content (with the html parts that should be initially hidden) gets processed!
这是我的建议。它利用这个解决方案来创建一个新的 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>
A bit more complicated, but I think this is a proper solution. The advantage is that flickering is prevented and that it works if JS is not enabled. And it doesn't require jQuery.
有点复杂,但我认为这是一个合适的解决方案。优点是可以防止闪烁,并且在未启用 JS 的情况下也能工作。而且它不需要 jQuery。
回答by robsch
After some time of thinking I've got the idea to the following solution. Compared to my other solutionI have reduced it to the essential part (and used thisto add a class by JS):
经过一段时间的思考,我有了以下解决方案的想法。与我的其他解决方案相比,我已将其简化为基本部分(并使用它通过 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>
The script tag gets executed immediately and adds a class to a container. Within this container there are some nested elements that get now hidden because the container has got the special class and there is a CSS rule that now has an effect.
脚本标签会立即执行并将类添加到容器中。在这个容器中,有一些嵌套的元素现在被隐藏了,因为容器有特殊的类,并且有一个 CSS 规则现在有效果。
Again, this happens before the remaining html gets processed (prevents blinking). And also, if JS is disabled, all the elements are visibly by default - what may be called Progressive enhancement.
同样,这发生在剩余的 html 被处理之前(防止闪烁)。而且,如果 JS 被禁用,默认情况下所有元素都是可见的 - 这可能被称为Progressive Enhancement。
Not sure if this works in every browser. But IMO it would be simple and neat solution.
不确定这是否适用于每个浏览器。但 IMO 这将是简单而整洁的解决方案。
回答by Darkerstar
you can apply "display: none" in a CSS class.
您可以在 CSS 类中应用“display: none”。
Because the order which a browser have to read some HTML code in order for the JavaScript to find the Element. You have to mark the element hidden, as the browser reads your HTML.
因为浏览器必须读取一些 HTML 代码才能让 JavaScript 找到 Element。您必须将元素标记为隐藏,因为浏览器会读取您的 HTML。
How ever you can also insert the HTML in your JavaScript, and you can call hide before it is rendered.
您还可以如何在 JavaScript 中插入 HTML,并且可以在呈现之前调用 hide。
回答by Coen Damen
What I always do is create an empty div. And if some data inside that component needs to be shown, I asynchronously load data (i.e. html) into it using $.ajax().
我总是做的是创建一个空的 div。如果需要显示该组件内的某些数据,我会使用 $.ajax() 将数据(即 html)异步加载到其中。
No need for an extra lib.
不需要额外的库。