实现不引人注目的Javascript [英] Implementing Unobtrusive Javascript
问题描述
我正在重做一个旧网站,并专注于使Javascript / jQuery尽可能不引人注目。我在寻找项目的一部分的一些建议:UJ要求,如果Javascript在浏览器中关闭,所有的网站内容仍然可供用户。我的网站的一部分有一个大的项目列表。列表中的每个项目都有自己的描述,它使用CSS显示: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?
推荐答案
基本上你可以插入一个类no-js html 元素,像这样
basically you can insert a class "no-js" in your html
element, like so
<html class="no-js" lang="en">
如果客户端上启用了javascript,您很快就会删除该类(使用 modernizr 或更简单的程式码片段,例如
and if javascript is enabled on the client you soon remove that class (using modernizr or a simpler code snippet like
<head>
<script>
(function(d) {
d.className = d.className.replace(/(^|\b)no-js(\b|$)/, 'js');
}(document.documentElement));
</script>
...
</head>
这样可以避免 .no-js 和<$ c $,即可避免-fouc-v3 /rel =nofollow> FOUC c> .js 类在css中的规则如下:
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:
.yourlistitems {
display: block;
}
.js .yourlistitems {
display: none;
}
此方法也由 H5BP 使用
请注意,你不需要真正需要在每个规则前面加上 .no-js
类:思考渐进增强和unobtrusive javascript,你将首先编写代码和风格一个也可以不使用javascript的页面,那么你将添加功能(和样式特殊性,在 .js
类之前)
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)
这篇关于实现不引人注目的Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!