One of the sweet parts in the simplified HTML5 spec was allowing A
elements to wrap DIV
s and other block level elements. For too long we added JavaScript listeners and window.location
redirects when a wrapping A
would have probably sufficed. But there are also times when the wrapping A
wouldn't work -- for example, a block with A
elements already within it -- you just want clicks on anything else within the parent to land at a given location.
简化HTML5规范中最甜蜜的部分之一是允许A
元素包装DIV
和其他块级元素。 很长时间以来,当包装A
可能已足够时,我们添加了JavaScript侦听器和window.location
重定向。 但是有时候,包装A
不能正常工作-例如,其中已经包含A
元素的块-您只希望单击父对象中的任何其他对象以将其放在指定位置。
Of course a basic listener like this would work:
当然,像这样的基本侦听器将起作用:
someElement.addEventListener('click', function(e) {
// not important what the URL is but assume it's available on
// the element in a `data-src` attribute
window.location = someElement.get('data-url');
});
...but it would succumb to one of my biggest pet peeves: COMMAND+CLICK
'ing a block and the link opening in the same window. The closer we can get custom-coded blocks to native browser functionality the better. So take a moment and fix your event listener callbacks:
...但是它会屈服于我最大的烦恼之一: COMMAND+CLICK
'阻止一个块,并且链接在同一窗口中打开。 我们越接近获得自定义编码的块来获得本机浏览器功能越好。 因此,花点时间修复您的事件监听器回调:
someElement.addEventListener('click', function(e) {
var url = someElement.get('data-url');
if(e.metaKey || e.ctrlKey || e.button === 1) {
window.open(url);
}
else {
window.location = url;
}
});
I've implemented this on my blog and it's something I keep in mind whenever I use a window.location
redirect. It's a minimal code addition but a major usability boost!
我已经在博客上实现了这一点,每当我使用window.location
重定向时,我都会记住这一点。 这是最少的代码添加,但大大提高了可用性!