惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
Security Latest
Security Latest
C
Cisco Blogs
P
Palo Alto Networks Blog
Know Your Adversary
Know Your Adversary
Project Zero
Project Zero
C
Cyber Attacks, Cyber Crime and Cyber Security
NISL@THU
NISL@THU
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Secure Thoughts
P
Privacy International News Feed
V
Vulnerabilities – Threatpost
D
Docker
Google Online Security Blog
Google Online Security Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Recent Announcements
Recent Announcements
T
The Exploit Database - CXSecurity.com
G
Google Developers Blog
Schneier on Security
Schneier on Security
小众软件
小众软件
爱范儿
爱范儿
GbyAI
GbyAI
J
Java Code Geeks
T
Tailwind CSS Blog
Cisco Talos Blog
Cisco Talos Blog
The Hacker News
The Hacker News
D
DataBreaches.Net
Blog — PlanetScale
Blog — PlanetScale
TaoSecurity Blog
TaoSecurity Blog
MyScale Blog
MyScale Blog
B
Blog RSS Feed
Cyberwarzone
Cyberwarzone
有赞技术团队
有赞技术团队
Martin Fowler
Martin Fowler
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Securelist
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Y
Y Combinator Blog
S
Schneier on Security
Latest news
Latest news
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 叶小钗
F
Fortinet All Blogs
M
MIT News - Artificial intelligence
PCI Perspectives
PCI Perspectives
V
V2EX
V2EX - 技术
V2EX - 技术
O
OpenAI News
W
WeLiveSecurity

Mathias Bynens

A horrifying globalThis polyfill in universal JavaScript JavaScript engine fundamentals: optimizing prototypes JavaScript engine fundamentals: Shapes and Inline Caches Asynchronous stack traces: why await beats Promise#then() ECMAScript regular expressions are getting better! Unicode property escapes in JavaScript regular expressions ES2015 const is not about immutability Valid JavaScript variable names in ES2015 Unicode-aware regular expressions in ES2015 Dear Google, please fix plain text emails in Gmail PBKDF2+HMAC hash collisions explained JavaScript has a Unicode problem Processing Content Security Policy violation reports Hiding JSON-formatted data in the DOM with CSP enabled Loading JSON-formatted data with Ajax and xhr.responseType='json' Reserved keywords in JavaScript How to support full Unicode in MySQL databases How to speedrun Dropbox’s Dropquest 2012 Unquoted font family names in CSS Unquoted property names / object keys in JavaScript Valid JavaScript variable names in ES5 CSS character escape sequences JavaScript’s internal character encoding: UCS-2 or UTF-16? The smallest possible valid (X)HTML documents JavaScript character escape sequences JavaScript foo.prototype.bar notation Ambiguous ampersands HTML element + attribute notation How I detect and use localStorage: a simple JavaScript pattern Unquoted attribute values in HTML and CSS/JS selectors The end-tag open (ETAGO) delimiter Using the oninput event handler with onkeyup/onkeydown as its fallback Everything you always wanted to know about touch icons In defense of CSS hacks — introducing “safe CSS hacks” AirPlay video support in iOS Safari — a bookmarklet Completing Dropbox’s Dropquest 2011 in 60 seconds Using CSS without HTML How to create simple Mac apps from shell scripts Using setTimeout to speed up window.onload Bulletproof JavaScript benchmarks Thoughts on Safari Reader’s generated HTML How to enable Safari Reader on your site? The XML serialization of HTML5, aka ‘XHTML5’ The id attribute got more classy in HTML5 The three levels of HTML5 usage The HTML5 document.head DOM tree accessor Displaying hidden elements like <head> using CSS Inline <script> and <style> vs. external .js and .css — what’s the size threshold? Using Showdown/PageDown with and without jQuery
Bulletproof HTML5 <details> fallback using jQuery
Mathias · 2010-04-18 · via Mathias Bynens

The HTML5 <details> element is currently not natively supported in any browser natively supported in Chrome 12 and up. This makes it a little hard to guess how exactly this new element will behave, but reading the spec gives us a pretty good idea. What’s clear is the following:

A details element represents a disclosure widget from which the user can obtain additional information or controls.

This information is hidden by default. It can be made visible by adding the boolean open attribute to the <details> element. After that, the user can toggle the visibility by clicking the <summary>.

The summary element represents a summary, caption, or legend for the rest of the contents of the summary element’s parent details element, if any. If there is no child summary element, the user agent should provide its own legend (e.g. “Details”).

Note that while the spec describes what should happen in case the <summary> element is omitted, it’s still invalid to do so.

It appears to me the summary element should be keyboard accessible as well. You should be able to tab through all different interactive elements (such as links, buttons, form elements), and guess what — summary is one of them. After focusing it with the keyboard, it would be nice to just hit Enter or Space to toggle visibility of the <details> element’s contents. The HTML spec doesn’t say anything about this matter, though.

Note that details got included into HTML5 because it’s such a common behavior for web sites and apps — so common it should be possible to do this without the need for additional scripting to make the whole thing work. However, HTML5 is still a work in progress. The <details> element is not even implemented yet. In the meantime, it’s important to provide a fallback/polyfill when using new features that aren’t (fully) supported cross-browser.

CSS, JavaScript, and jQuery to the rescue

Luckily it’s pretty easy to make <details> work cross-browser using a combination of CSS, (plain) JavaScript, and jQuery.

Detecting native <details> support with JavaScript

First, let’s add class="no-details" to the html element if JavaScript is enabled and the browser does not support <details> natively. This will allow us to write CSS specifically for the occasion our scripts will actually be executed. Adding the class can be done in various ways, but the one I prefer is by placing the following snippet in the <head>:

<script>
	// Don’t use this! See note below.
	if (!('open' in document.createElement('details'))) {
 		document.documentElement.className += ' no-details';
	}
</script>

Update: Chrome 10 recognizes the open attribute for <details> elements, even though it doesn’t support rendering the element correctly yet. This means the above feature detection method has become unreliable. I’ve now created a more robust feature test for <details>/<summary> support:

var isDetailsSupported = (function(doc) {
	var el = doc.createElement('details');
	var fake;
	var root;
	var diff;
	if (!('open' in el)) {
		return false;
	}
	root = doc.body || (function() {
		var de = doc.documentElement;
		fake = true;
		return de.insertBefore(doc.createElement('body'), de.firstElementChild || de.firstChild);
	}());
	el.innerHTML = '<summary>a</summary>b';
	el.style.display = 'block';
	root.appendChild(el);
	diff = el.offsetHeight;
	el.open = true;
	diff = diff != el.offsetHeight;
	root.removeChild(el);
	if (fake) {
		root.parentNode.removeChild(root);
	}
	return diff;
}(document));

So after that, we can just do something like:

<script>
	if (!isDetailsSupported) {
		document.documentElement.className += ' no-details';
	}
</script>

Note that Modernizr currently doesn’t detect <details> support. I’m sure it will be included soon. Update: My feature test for <details> is now included in the Modernizr repository.

Adding some basic style

Now we can add some fundamental styling to the details element and its children.

/* Default browser styles for <details> and <summary> */
details { display: block; }
summary { display: list-item; }

/* The following styles will only get applied if JavaScript is enabled and <details> is not natively supported */

/* Add focus styles (for keyboard accessibility) */
.no-details summary:hover, .no-details summary:focus { background: #ddd; }

/* The following styles are not really needed, since the jQuery script takes care of hiding/displaying the elements. */
/* However, we’re still gonna use CSS as well to prevent FOUC in browsers that understand these selectors. */
/* Remember: by default (and probably most of the time), the contents of the <details> element are hidden. */

/* Hide all direct descendants of every <details> element */
/* Note that IE6 doesn’t support the child selector; we’ll work around that using jQuery later */
.no-details details > * { display: none; }

/* Make sure summary remains visible */
.no-details details summary { display: list-item; }

/* Apply a pointer cursor upon hover to indicate it’s a clickable element. These styles can be applied regardless of whether the fallback is needed */
summary { cursor: pointer; }

The jQuery magic

I’ve written a jQuery plugin that makes it very easy to emulate <details>/<summary> in browsers that don’t support these elements yet. Check out the code on GitHub.

After including jQuery and the plugin, you can just write something like this to emulate <details>/<summary> where necessary:

$('details').details();

The result of the feature test is stored in $.fn.details.support, which will be true if the browser natively supports <details> and <summary>, and false otherwise:

// Conditionally add a classname to the `<html>` element, based on native support
$('html').addClass($.fn.details.support ? 'details' : 'no-details');

The plugin will also add the appropriate ARIA annotations for optimal accessibility. This will be done even in browsers that natively support <details>, just in case.

Demo

I’ve put up a demo page with heavily commented source code as well. Enjoy!

This fallback works in all A-grade browsers, including IE6. It will only be executed if the <details> element is not natively supported in the browser. If it isn’t, and JavaScript is disabled, all elements will still be visible to the user.

Note that you should never pull in a 25 KiB JavaScript library just to make <details> work — this solution should only be used in cases where jQuery is used already. Of course it’s possible to rewrite this as plain JavaScript, but I’ll leave that as an exercise to the reader ;)