实现不显眼的 Javascript
我正在重新设计一个旧网站,并专注于使 Javascript/jQuery 尽可能不引人注目。我正在寻找有关该项目一部分的一些建议:UJ 要求,如果浏览器中关闭了 Javascript,则所有网站内容仍然可供用户使用。我网站的一部分有大量的项目列表。列表中的每个项目都有自己的描述,默认情况下使用 CSS display:none 隐藏它。单击该项目会使用 jQuery .toggle(): 切换描述的可见性,因此无法使用 Javascript(无论出于何种原因)的人将永远不会看到它。如果我使用 Javascript/jQuery 而不是 CSS 来隐藏描述,那么当页面加载时它们都会立即可见,这是我想避免的。那么最好的解决方案是什么?
I'm reworking an old website and am focusing on making the Javascript/jQuery as unobtrusive as possible. I'm looking for some advice on one part of the project: UJ requires that, if Javascript is turned off in a browser, all the site content is still available to the user. One part of my site has a large list of items. Each item in the list has it's own description, which uses CSS display:none to hide it by default. Clicking on the item toggles the visibility of the description using jQuery .toggle():, so a person unable to use Javascript (for whatever reason) would never see it. If I use Javascript/jQuery rather than CSS to hide the descriptions, they are all momentarily visible when the page loads, which I want to avoid. So what's the best solution?
发布评论
评论(3)
基本上你可以在
html
元素中插入一个类“no-js”,就像这样,如果客户端上启用了 javascript,你很快就会删除该类(使用 modernizr 或更简单的代码片段
,这样您就可以避免 FOUC(无样式内容的闪存) 只需在 css 规则中使用
.no-js
和.js
类,如下所示:这种方法也被 H5BP
使用
请注意,您实际上并不需要在每个规则前面添加
.no-js
类:考虑“渐进式增强”和“不显眼的 javascript”,您将首先为页面编写代码和样式无需 JavaScript 即可工作,然后您将添加功能(和样式特异性,在.js
类前面)basically you can insert a class "no-js" in your
html
element, like soand if javascript is enabled on the client you soon remove that class (using modernizr or a simpler code snippet like
in this way you can avoid the FOUC (flash of unstyled content) simply using
.no-js
and.js
class in the css rules like so:this approach is also used by H5BP
Note that you don't really need to prepend
.no-js
class to each rule: thinking in terms of "progressive enhancement" and "unobtrusive javascript" you will code and style first for a page that also works without javascript, then you will add functionality (and style specificity, prepending the.js
class)您是否考虑过使用类似于 Modernizr 实现的方法?
CSS 类通过脚本添加到 HTML 标记,导致不同的 CSS 选择器匹配。
Have you thought about using a method like the one implemented with Modernizr?
CSS classes are added to the HTML tag by a script that causes different CSS selectors to match.
由于潜在的异步操作,无法判断这是否真的有帮助,但您可以添加一个
,它会在您的