【DOM编程艺术】图片库改进版

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>查看图片</title>
<style type="text/css">
ul,li{ list-style:none;}
ul li{ line-height:24px; float:left; padding:1em;}
img{ display:block; clear:both;}
</style>
</head>

<body>
<h1>Snapshots</h1>
<ul id='imagegallery'>
    <li><a href="images/1.jpg"  title="pic01111">第一张图片</a></li>
    <li><a href="images/2.jpg"  title="pic02222">第二张图片</a></li>
    <li><a href="images/3.jpg" title="pic03333">第三张图片</a></li>
    <li><a href="images/4.jpg" title="pic04444">第四张图片</a></li>
</ul>
<img id='placeholder' alt='My Image Gallery'  src="images/placeholder.gif"/>
<p  id="description">Choose an image</p>
<script>
window.onload=prepareGallery;
function prepareGallery(){
    if(!document.getElementById ) return false;
    if(!document.getElementsByTagName) return false;
    if(!document.getElementById('imagegallery')) return false;
    var gallery=document.getElementById('imagegallery');
    var links=gallery.getElementsByTagName('a');
    for(var i=0;i<links.length;i++){
        links[i].onclick=function(){
            showpic(this); return !showpic(this); return showpic(this)?false:true;
            return false; 
        }
     links[i].onkeypress=links[i].onclick; //疑问:测试的时候firefox下不写此代码也是可以tab切换的,写此代码后第1张图片切换成功后就不动了,无法切换第二张图片 } }
function showpic(whichpic){ if( !document.getElementById('placeholder')) return false; var placeholder=document.getElementById('placeholder');
if(placeholder.nodeName!='IMG') return false; //*******nodeName属性总是返回一个大写字母的值,即使元素在HTML文档里是小写字母。 placeholder.setAttribute(
'src',whichpic.getAttribute('href')); //或者placeholder.src=source (var source=whichpic.href); if(document.getElementById('description')){ var text=whichpic.getAttribute('title')?whichpic.getAttribute('title'):' '; //三元操作符 var description=document.getElementById('description');
if(description.firstChild.nodeType==3){ description.firstChild.nodeValue
=text;
} }
return true; }
</script> </body> </html>

红色javascript代码部分是为了考虑向后兼容性而写!也不要做太多的假设!

return !showpic(this);

 解析:此代码主要是解决当showpic函数里placeholder不存在的时候(代码就会返回false.也就导致了默认链接不可点击)

            showpic()里应该是如果图片交换成功,return true; 如果不成功,返回false;

           所以!showpic()为false的时候默认链接不可点击就对了 

links[i].onkeypress=links[i].onclick;

 解析:onkeypress事件处理函数很容易出问题。用户每按下一个一个按键都会触发它。在某些浏览器里,甚至包括Tab键!这意味着如果绑定在onkeypress事件上的处理函数都会返回false,那些只能使用键盘访问的用户将永远无法离开当前链接。

          加上以后存在的问题---只要图片切换成功,showpic函数将返回false;

         幸运的是,onclick事件处理函数比我们想象的更聪明。虽然它的名字“onclick”给人一种只与鼠标点击动作相关联的印象,但事实并非如此:在几乎所有的浏览器里,用TAB键移动到某个链接然后按下回车键的动作也会触发onclik事件

         最好不要使用onkeypress事件处理函数。onclick事件处理函数已经能满足需要。虽然它叫“onclick”,但它对键盘访问的支持相当完美

转载于:https://www.cnblogs.com/positive/p/3662533.html

猜你喜欢

转载自blog.csdn.net/weixin_34128237/article/details/93495759