有没有一种只使用 CSS3,而不需要 JS 或任何 JS 库就可以为链接添加键盘导航的方法?具体来说,我创建了一个纯 CSS3 的灯箱效果,并有一堆图片,但我想要使用左右箭头键在图片之间导航,而不必在屏幕上的任何地方点击,并使用 ESC 键来实现“取消”按钮的效果(类似于关闭)。
http://jsfiddle.net/darkyen/NUtnX/
但是我想在开始之前警告您,任何“模糊”都会导致此操作失败。 因此,更好的JavaScript代码变体如下所示
JavaScript代码
实现您想要的JavaScript代码将包含非常少量的JavaScript。假设您的标记是:
因此,您可以简单地分配一小段JavaScript代码。
(function(){
var slide = 0, // Current slide
max = 10, // Maximum Number of slides
ele = document.getElementById("show");
document.addEventListener('keydown',function(e){
e.preventDefault();
e.stopPropagation(); // To stop more event stuff and default behaviour
key = e.keyCode; // To find out what key is this
if( key === 39 ){
// Right arrow
// Aha we incremented the value!
slide++;
slide %= (max+1);
// Increase the value of slide by 1 and keep em in limits
}else if( key === 37){
slide = (--slide >= 0)?slide: ( slide + max );
// Will decrement the slide value by 1 and if they are less then 0 then will cycle it to the last slide
}
ele.className.replace(/slide[0-9]/gi,'slide'+slide);
// wasn't hard now was it ?
});
})();
以上最小的JavaScript代码可以完成更改幻灯片的任务,或者您可以随时查看impress.js的源代码。