简体   繁体   English

切换css for Javascript已禁用

[英]switching css for Javascript is disabled

I´m having a problem switching css when Javascript is disabled. 我在Javascript被禁用时切换css有问题。

I have this code: 我有这个代码:

<style type="text/css">.nonjsonly{display:none;}.jsonly{display:inline;}</style>
<noscript><style type="text/css">.nonjsonly{display:inline}.jsonly{display:none}</style></noscript>

Witch is working right now, but W3C doesn´t approve it, as noscript is illegal in html head (And the code is in head). Witch现在正在工作,但是W3C并没有批准它,因为noscript在html头部是非法的(并且代码在头部)。

Any idea how it can be made? 知道怎么做吗?

Thanks in advance 提前致谢

A more appropriate way to handle this is to place your non-js CSS first, without any <noscript> tag, followed by a script which loads a stylesheet for JavaScript-capable clients. 处理此问题的更合适的方法是首先放置非js CSS,不带任何<noscript>标记,然后是为支持JavaScript的客户端加载样式表的脚本。 The JS-capable css should then cascade to override the basic sheet. 然后,具有JS功能的css应该级联以覆盖基本表。

<style type='text/css'>
  /* baseline CSS for all clients */
</style>

<!-- Then a script loads an additional stylesheet which cascades to override the baseline -->
<!-- Obviously, won't get loaded by noscript clients -->
<script type='text/javascript'>
  document.write("<link type='text/css' rel='stylesheet' href='/path/to/js-friendly.css' />");
</script>

Put the default css first: 首先放置默认的css:

<style type="text/css" src="default.css" />

so the non-JS styles apply to everyone. 所以非JS风格适用于每个人。 Then use some JS to dynamically load the "js-enabled" styles: 然后使用一些JS动态加载“js-enabled”样式:

<script type="text/javascript">
    css = document.createElement('link');
    css.setAttribute('rel', 'stylsheet');
    css.setAttribute('type', 'text/css');
    css.setAttribute('href', 'js-styles.css'); // change as needed
    document.getElementsByTagName('head')[0].appendChild(css);
</script>

which will override the non-js styles. 这将覆盖非js样式。

you can do something like this 你可以做这样的事情

<script>
    document.getElementsByTagName('body')[0].className += ' jsActive';
</script>

that script write the "jsActive" Class to the Body Element if Javascript is avalible. 如果Javascript是可用的,该脚本将“jsActive”类写入Body元素。 You don´t have a "noJavascipt" Class, but you can select with CSS and build you Funcitons 你没有“noJavascipt”类,但你可以选择CSS并构建你的Funcitons

  1. Use 1 stylesheet 使用1个样式表
  2. Add .js to the html element via JavaScript 通过JavaScript将.js添加到html元素
  3. For styles that require JavaScript, prefix your selector with .js 对于需要JavaScript的样式,请在选择器前加上.js

Ex: 例如:

#foo

becomes

.js #foo

Even better, use Modernizr to detect more advanced features (it'll automatically add .js too). 更好的是,使用Modernizr来检测更高级的功能(它也会自动添加.js )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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