javascript dom编程艺术笔记之图片库的改进

dom的操作要遵守的原则

1.平稳退化

2.分离javascript

3.向后兼容

4.性能考虑

 

改进后的显示图片方法

 

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){
        discription.firstChild.nodeValue=text;
     }
    }
    return true;
}

 

新添加的分离html和javascript方法

function prepareGallery(){
    if(!document.getElementById) return false;
    if(!document.getElementByTagName) return false;
    if(!document.getElementById("imagegallery")) return false;
    var gallery=document.getElementById("imagegallery");
    var link=gallery.getElementByTagName("a");
    for(var i=0; i<link.length ;i++){
        link[i].onclick=function(){
            return showpic(this) ? false:true;
        }
    }
}

 

添加事件的方法

function addLoadEvent(func){
    var oldonload=window.onload;
    if(typeof window.onload!='function'){
        window.onload=func;
    }else{
        window.onload-function(){
            oldonload();
            func();
        }
    }
 }
posted @ 2016-03-28 12:45  有礼貌的Wu  阅读(548)  评论(0)    收藏  举报