问题
All the answers I could find recommended adding display:none to css... but for a user without javascript, they will never see the element.
jQuery(document).ready(function($){
$('#toggleElm').hide();
$('#toggleBtn').click(function(){
$('#shareLink').slideToggle();
})
});
still results in an element that appears and disappears during page load because the page begins rendering before the DOM has finished these days.
<script type='javascript'>
document.write("<style type='text/css'> #toggleElm {display:none} </style>");
</script>
at the top of the body just seems too hacky.
回答1:
to prevent the javascript FOUC and let your page fully accessible you should apply a .no-js
class in <html>
element and then use that class to style your elements, exactly as html5 boilerplate+modernizr do
#toggleElm { display: none; }
.no-js #toggleElm { display: block; }
of course you have to remove that class via javascript soon in the <head>
of your document, with a script like this
<script>
(function(d) {
d.className = d.className.replace(/(^|\b)no\-js(\b|$)/, 'js');
}(document.documentElement));
</script>
so if javascript is enabled, it will turn the .no-js
class into .js
class.
Using this approach, your page is still accessible even when javascript is not available, because in that scenario the last CSS rule will be applied, leaving your elements visible and accessible.
回答2:
An element is registered in the DOM as soon as it's closing tag has been parsed.
Therefore, you can hide the element straight after that tab;
<div id="toggleElm">Foo</div>
<script>
// Note: No $(document).ready()!
$('#toggleElm').hide();
</script>
Obviously this depends on jQuery being loaded already (i.e. not being included at the bottom of the page). If this is the case, revert to plain ol' JavaScript:
<div id="toggleElm">Foo</div>
<script>
document.getElementById('toggleElm').style.display = 'none';
</script>
回答3:
If you don't want to wait for the document to be ready, don't wait for the document to be ready.
<p id="foo">Stuff...</p>
<script>
document.getElementById('foo').style.display = 'none';
</script>
来源:https://stackoverflow.com/questions/9995791/how-to-hide-an-element-to-be-toggled-with-jquery-while-maintaining-progressive-e