简体   繁体   中英

Changing display property using javascript messes up formatting

I part of a webpage that should only be shown if javascript is enabled.

I have tried the following:

Method 1: I set the class to display: hidden; then change it if javascript works by overriding it...

<script type="text/javascript"> 
//<![CDATA[
$(document).ready(function() {
    document.getElementById('only-show-if-js-enabled').style.display = 'block';});
//]]>
</script> 


and also

Method 2: I change the id to one has has display set as block (or auto)...

<script type="text/javascript"> 
//<![CDATA[
$(document).ready(function() {
    $("#js-not-enabled").attr('id', 'js-enabled');
});
//]]>
</script> 


Both methods seem to cause the actual formatting to be messed up, the first ignores my css that the list style is none, the second that overflow is hidden.

What's going on?

UPDATE: Rather embarrassingly I had overflow set to auto , and just thought it was set to hidden. My mistake.

Thank you for both replies though, they both shed some light on best practices etc. cheers.

This should do it http://jsfiddle.net/kkwan/1/

$('#only-show-if-js-enabled').show();

Right, i kinda missed the whole issue here... Uhm, does the css work without the code you mentioned if you change the display: none; to display: block; Or if you firebug it or something..?

the modern approach for this kind of thing is to have you document ready function do this:

<script type="text/javascript"> 
//<![CDATA[
$(document).ready(function() {
    $("body").addClass("js");
//]]>
</script>

then in your CSS you can use this as a hook to only show things for JS-enabled (or disabled) devices.

#OnlyShowWhenJsDisbaled { display: none; } /*hide by default */
body.js #OnlyShowWhenJsEnabled { display: block; } /*show when js has been confirmed*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM