Как скрыть части HTML, когда JavaScript отключен?

Установите Testdriven.NET и используйте «Test With -> Debugger».

17
задан Peter Mortensen 2 October 2011 в 18:34
поделиться

5 ответов

here's a video tutorial on how this can be done with jQuery: http://screenr.com/ya7

Code:

<body class="noscript">
<script>
$('body').removeClass('noscript');
</script>
</body>

And then just hide the relevant elements under body.noscript accordingly.

edit However, JQuery might be bloated for a small fix like this one, so I suggest Zauber Paracelsus' answer since it does not require JQuery.

7
ответ дан 30 November 2019 в 10:17
поделиться

By the way, is it worth the effort nowadays?

Yes, it's worth worrying about accessibility. You should use progressive enhancement where possible, i.e. make a basic version that works without scripting and then add the scripting functionality on top of it.

A simple example would be a pop-up link. You could make one like this:

<a href="javascript:window.open('http://example.com/');">link</a>

However, this link wouldn't work if someone, say, middle-clicked or tried to bookmark it, or had scripts disabled etc. Instead, you could do the same thing like this:

<a href="http://example.com/" 
   onclick="window.open(this.href); return false;">link</a>

It's still not perfect, because you should separate the behavior and structure layers and avoid inline event handlers, but it's better, because it's more accessible and doesn't require scripting.

4
ответ дан 30 November 2019 в 10:17
поделиться

Default the bits you want to hide as styled as display:none and switch them on with jQuery or JavaScript.

10
ответ дан 30 November 2019 в 10:17
поделиться

The jQuery way:

$(document).ready(function(){
    $("body").removeClass("noJS");
});

Pseudo CSS

body
    .no-js-content
        display: none;
body.noJS
    .main
        display: none;
    .no-js-content
        display: block;

HTML

<body class="noJS">
    <div class="main">
        This will show if JavaScript is activated
    </div>
    <div class='no-js-content'>
        This will show when JavaScript is disabled
    </div>
</body>
2
ответ дан 30 November 2019 в 10:17
поделиться

If the content only makes sense when JavaScript is enabled, then it should be inserted by the JavaScript code directly rather than being rendered. This could either be done by simply having HTML templates as strings within your JavaScript code, or using Ajax if the HTML is more complex.

As mentioned by Reinis I. this is the idea of Progressive Enhancement.

Regarding the CSS techniques of using a class name on the body tag, I would advise doing this the other way around and adding a 'js-enabled' class to the body tag with JavaScript that would alter the page CSS. This fits in with my above comment about keeping all initial HTML 'non-JavaScript friendly'.

2
ответ дан 30 November 2019 в 10:17
поделиться
Другие вопросы по тегам:

Похожие вопросы: