JavaScript案例分析:图片库改进版(2)

1.优化

     showPic函数中里仍存在一些需要处理的假设

    ①检查title属性是否存在,可以测试它是否为null

 var text=whichpic.getAttribute("title")?whichpic.getAttribute("title"):"";

    ②检查placeholder元素是否存在,但需要假设那是张照片。

        nodeName属性总是返回一个大写字母的值,即使在HTML文档中是小写字母

  if(placeholder.nodeName!="IMG")return false;

    ③检查description元素的第一个子元素是否为文本节点

 if(description.firstChild.nodeType==3){
     description.firstChild.nodeValue=text;
}

    ④showPic()的完整代码

  function showPic(whichpic){
       if(!document.getElementById("placeholder")) return false;
       var source=whichpic.getAttribute("href");
       var placeholder=document.getElementById("placeholder");
       if(placeholder.nodeName!="IMG") return false;
       placeholder.setAttribute("src",source);
       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;
 }

  

2.键盘访问

  links[i].onclick=function(){
      return showPic(this)?false:true;
  }

     上面代码存在一个假定:用户只会用鼠标来点击这个链接。实际上,并非所有用户都是使用鼠标来浏览Web的。

      下面我们将介绍用于处理键盘事件的onkeypress事件处理函数。

       ①onkeypress事件与onclick事件触发同样的行为

    第一种方式:

  links[i].onclick=function(){
     return showPic(this)?false:true;
 }
  
  links[i].onkeypress=function(){
     return showPic(this)?false:true;
  }

    第二种方式:

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

       ②小心onkeypress

          然而onkeypress这个事件处理函数很容易出问题,用户每按下一个按键都会触发它。

          而几乎在所有的浏览器中,用Tab键移动到某个链接然后按下回车也会触发onclick事件。

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

3.把JavaScript与CSS结合起来

     在把内嵌事件处理函数移出标志文档时,我们在文档里为JavaScript代码留下了挂钩

<ul id="imagegallery">

    我们可以使用这个挂钩用于css样式表中:

   ①

#imagegallery li{
   display:inline; 
}
<link rel="stylesheet" href="styles/layout.css" type="text/css" media="screen"/>

4.DOM Core和HTML-DOM

      ①DOM Core:可以用来处理任何一种标记语言编写出来的文档

        getElementById

        getElementsByTagName

        getAttribute

        setAttribute

      ② HTML-DOM:提供了许多描述各种HTML元素的属性.

        onclick    

        element.getAttribute("src")  等价于 element.src   (这些方法与属性互换)

      ③

       同样的操作可以只使用DOM Core也可以使用HTML-DOM来实现。通常HTML-DOM更短的。但是它们都只能用来处理Web文档。

 placeholder.setAttribute("src",source);
// DOM Core

 placeholder.src=source;
// HTML-DOM

猜你喜欢

转载自blog.csdn.net/rachel9798/article/details/82848083