dom编程艺术章12

Posted linbudu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了dom编程艺术章12相关的知识,希望对你有一定的参考价值。

function addLoadEvent(func){//添加事件函数
    var oldonload = window.onload;
    if(typeof window.onload != ‘function‘){
        window.onload = func;
    }else{
        window.onload = function(){
            oldonload();
            func();
        }
    }    
}

function insertAfter(newElement,targetElement){//自带的是insertBefore()方法
    var parent = targetElement.parentNode;
    if( parent.lastChild == targetElement){
        parent.appendChild(newElement);
    }else{
        parent.insertBefore(newElement,targetElement.nextSibling);
    }
}

function addClass(element,value){
    if(!element.className){
        element.className = value;
    }else{
        newClassName = element.className;
        newClassName += ‘ ‘;
        newClassName += value;
        element.className = newClassName;
    }
}

function highlightPage(){
    if( !document.getElementById) return false;
    if( !document.getElementsByTagName ) return false;
    var headers = document.getElementsByTagName(‘header‘);
    if( headers.length == 0) return false;
    var navs = headers[0].getElementsByTagName(‘nav‘);
    if( navs.length == 0 ) return false;
    var links = navs[0].getElementsByTagName(‘a‘);
    var url = window.location.href;
    for(var i=0;i<links.length;i++){
        var linkurl = links[i].getAttribute(‘href‘);
        if( url.indexOf(linkurl) != -1 ){//如果在url(如…….html/live.html)中查找到了linkurl(如live.html),就添加here类
            links[i].setAttribute(‘href‘,‘#‘);
            links[i].className = ‘here‘ ;
        }
    }
}

function prepareSlideshow(){//图片库 第九章好像?
    if(!document.getElementById(‘intro‘)) return false;
    var slideshow = document.createElement(‘div‘);
    slideshow.setAttribute(‘id‘,‘slideshow‘);
    var frame = document.createElement(‘img‘);
    frame.setAttribute(‘id‘,‘frame‘);
    frame.setAttribute(‘src‘,‘images/frame.gif‘);
    slideshow.appendChild(frame);
    var preview = document.createElement(‘img‘);
    preview.setAttribute(‘id‘,‘preview‘);
    preview.setAttribute(‘src‘,‘images/slideshow.gif‘);
    slideshow.appendChild(preview);
    var intro = document.getElementById(‘intro‘);
    insertAfter(slideshow,intro);
    var links = document.getElementsByTagName(‘a‘);
    for(var i=0;i<links.length;i++){
        links[i].onmouseover=function(){
            var destiation = this.getAttribute(‘href‘);
            if( destiation.indexOf(‘index.html‘) != -1){
                moveElement(‘preview‘,0,0,10);
            }
            if( destiation.indexOf(‘about.html‘) != -1){
                moveElement(‘preview‘,-150,0,10);
            }
            if( destiation.indexOf(‘photos.html‘) != -1){
                moveElement(‘preview‘,-300,0,10);
            }
            if( destiation.indexOf(‘live.html‘) != -1){
                moveElement(‘preview‘,-450,0,10);
            }
            if( destiation.indexOf(‘contact.html‘) != -1){
                moveElement(‘preview‘,-600,0,10);
            }
            
        }    
    }
}

function moveElement(elementID,final_x,final_y,interval){
    var elem = document.getElementById(elementID);
    if( !elem.style.left) {elem.style.left = 0;}
    if( !elem.style.top) {elem.style.top = 0;}
    var xpos = parseInt(elem.style.left);
    var ypos = parseInt(elem.style.top);
    var dist;
    if(elem.movement) { clearTimeout(elem.movement)}; 
    if( xpos == final_x && ypos == final_y ){
        return true;
    }
    if( xpos < final_x){
        dist = Math.ceil((final_x - xpos)/10);
        xpos = xpos + dist;
    }
    if( xpos > final_x){
        dist = Math.ceil((xpos - final_x)/10);
        xpos = xpos - dist;
    }
    if( ypos < final_y){
        dist = Math.ceil((final_y - ypos)/10);
        ypos = ypos + dist;
    }
    if( ypos > final_y){
        dist = Math.ceil((final_y - ypos)/10);
        ypos = ypos - dist;
    }
    elem.style.left = xpos +‘px‘;
    elem.style.top = ypos +‘px‘;
    var repeat = "moveElement(‘"+elementID+"‘,"+final_x+","+final_y+","+interval+")";
    elem.movement = setTimeout(repeat,interval);
}
//About
function prepareShowSection(){
    if( !document.getElementById) return false;
    if( !document.getElementsByTagName) return false;
    var article = document.getElementsByTagName(‘article‘);
    if( article.length == 0 ) return false;
    var nav = article[0].getElementsByTagName(‘nav‘);
    if( nav.length == 0 ) return false;
    var links = nav[0].getElementsByTagName(‘a‘);
    for(var i=0;i<links.length;i++){
        document.getElementsByTagName(‘section‘)[i].style.display = ‘none‘;
        var sectionId = links[i].getAttribute(‘href‘).split(‘#‘)[1];
        links[i].destination = sectionId;
        if( !document.getElementById(sectionId)) continue;
        links[i].onclick = function(){
            showSection(this.destination);
            return false;
        }
    }
    
}

function showSection(id){
    var sections = document.getElementsByTagName(‘section‘);
    for(var i=0;i<sections.length;i++){
        if(sections[i].getAttribute(‘id‘) != id){
            sections[i].style.display = ‘none‘;
        }else{
            sections[i].style.display = ‘block‘;
        }
    }
}

//photos
function preparePlaceholder(){
    if( !document.getElementById) return false;
    if( !document.getElementsByTagName ) return false;
    if( !document.getElementById(‘imagegallery‘)) return false;
    var placeholder = document.createElement(‘img‘);
    placeholder.setAttribute(‘id‘,‘placeholder‘);
    placeholder.setAttribute(‘src‘,‘images/placeholder.gif‘);
    var description = document.createElement(‘p‘);
    description.setAttribute(‘id‘,‘description‘);
    var text = document.createTextNode(‘choose an image‘);
    description.appendChild(text);
    var imagegallery= document.getElementById(‘imagegallery‘);
    insertAfter(description,imagegallery);
    insertAfter(placeholder,description);
}

function prepareGallery(){
    if( !document.getElementById(‘imagegallery‘)) return false;
    var imagegallery = document.getElementById(‘imagegallery‘);
    var links = imagegallery.getElementsByTagName(‘a‘);
    for(var i=0;i<links.length;i++){
        links[i].onclick = function(){
            return showpic(this);
        }        
    }
}

function showpic(whichpic){
    if( !document.getElementById(‘placeholder‘)) return true;
    var imageurl = whichpic.getAttribute(‘href‘);
    var placeholder = document.getElementById(‘placeholder‘);
    placeholder.setAttribute(‘src‘,imageurl);
    if( !document.getElementById(‘description‘)) return false;
    if( !whichpic.getAttribute(‘title‘)){
        var title = ‘‘;
    }else{
        var title = whichpic.getAttribute(‘title‘);
    }
    var description = document.getElementById(‘description‘);
    if( description.firstChild.nodeType == 3){
        description.firstChild.nodeValue = title;
    }
    return false;
}

//live
function stripeTables(){
    var tables = document.getElementsByTagName(‘table‘);
    for(var i=0;i<tables.length;i++){
        var rows = tables[i].getElementsByTagName(‘tr‘);
        var odd = false;
        for(var j=0;j<rows.length;j++){
            if( odd == false ){
                odd = true;
            }else{
                addClass(rows[j],‘odd‘);
                odd = false;
            }
        }
    }
}

function highlightRows(){//表格斑马线样式
    var tables = document.getElementsByTagName(‘table‘);
    for(var i=0;i<tables.length;i++){
        var rows = tables[i].getElementsByTagName(‘tr‘);
        for(var j=0;j<rows.length;j++){
            var oldClassname = rows[j].className;
            rows[j].onmouseover = function(){
                 addClass(this,‘highlight‘);
            }
            rows[j].onmouseout = function(){
                this.className = oldClassname;
            }
        }
    }
}

function displayAbbreviations(){
    if( !document.getElementsByTagName(‘abbr‘)) return false;
    var defs = new Array();
    var abbrs = document.getElementsByTagName(‘abbr‘);
    if( abbrs.length ==0) return false;
    for(var i=0;i<abbrs.length;i++){
        if( abbrs[i].childNodes.length <1) continue;
        var key = abbrs[i].firstChild.nodeValue;
        var definition = abbrs[i].getAttribute(‘title‘);
        defs[key] = definition;
    }
    var dlist = document.createElement(‘dl‘);
    for(var key in defs){
        var dtitle = document.createElement(‘dt‘);
        var dtitle_text = document.createTextNode(key);
        dtitle.appendChild(dtitle_text);
        var ddtitle = document.createElement(‘dd‘);
        var definition = defs[key];
        var ddtitle_text = document.createTextNode(definition);
        ddtitle.appendChild(ddtitle_text);
        dlist.appendChild(dtitle);
        dlist.appendChild(ddtitle);        
    }
    var header = document.createElement(‘h3‘);
    var header_text = document.createElement(‘Abbreviations‘);
    header.appendChild(header_text);
    var articles = document.getElementsByTagName(‘article‘);
    if( articles.length == 0) return false;
    articles[0].appendChild(header);
    articles[0].appendChild(dlist);
    
}

/*contact*/
function focusLabels(){
    var labels = document.getElementsByTagName(‘label‘);
    for( var i=0;i<labels.length;i++){
        if( !labels[i].getAttribute(‘for‘) ) continue;
        labels[i].onclick = function(){
            var id = this.getAttribute(‘for‘);
            if( !document.getElementById(id)) return false;
            var elem = document.getElementById(id);
            elem.focus();
        }
        
    }
}

function prepareForms(){
    for(var i=0;i< document.forms.length;i++){
        var thisform = document.forms[i];
        resetFields(thisform);
        thisform.onsubmit = function(){
            if(!validateForm(this)) return false;
            var article = document.getElementsByTagName(‘article‘)[0];
            if(submitFormWithAjax(this,article)) return false;
            return true;
        }
    }
}

function resetFields(whichform){
    if( Modernizr.input.placeholder )  return;
    for(var i=0;i< whichform.elements.length; i++){
        var element = whichform.elements[i];
        if(element.type == ‘submit‘) continue;
        var check = element.placeholder || element.getAttribute(‘placeholder‘);
        if( !check) continue;
        var placeholder = element.getAttribute(‘placeholder‘);
        //element.className = ‘placeholder‘;
        //element.value = placeholder;
        element.onfocus= function(){
            var text = this.placeholder || this.getAttribute(‘placeholder‘);
            if( this.value == text){
                this.value = ‘‘;
            }
            
        }
        element.onblur = function(){        
            if( this.value == ‘‘){
                this.className = ‘placeholder‘;
                this.value = this.placeholder || this.getAttribute(‘placeholder‘);
            }
        }
        element.onblur();
        
    }
}
/*表单*/
function validateForm(whichform){//有效性检验
    for(var i=0;i<whichform.elements.length;i++){
        var elem = whichform.elements[i];
        var elem_required = elem.required || elem.getAttribute(‘required‘);
        if( elem_required == ‘‘ || elem_required == ‘required‘){
            var elem_name = elem.name || elem.getAttribute(‘name‘);
            if( !isFilled(elem) ){
                alert(‘please fill in ‘+elem_name +‘  ‘+‘field.‘);
                return false;
            }
            if( elem.getAttribute(‘id‘) == ‘email‘){ //或者elem.type == ‘email‘
                if( !isEmail(elem)){
                    alert(‘请输入正确的邮箱地址‘);
                    return false;
                }
            }
        }
    }
    return true;
}



function isFilled(field){
    if(field.value.replace(‘ ‘,‘‘).length == 0) return false;
    var placeholder = field.placeholder || field.getAttribute(‘placeholder‘);
    return (field.value != placeholder);
    
}

function isEmail(field){
    return (field.value.indexOf(‘@‘) != -1   && field.value.indexOf(‘.‘) != -1); 
}

/*ajax*/
function submitFormWithAjax(whichform,thetarget){
    var request = getHTTPObject();
    if(!request) return false;
    displayAjaxLoading(thetarget);
    var dataParts = [];
    for(i=0;i<whichform.elements.length;i++){
        var elem = whichform.elements[i];
        dataParts[i] = elem.getAttribute(‘name‘) + ‘=‘ + encodeURIComponent(elem.value);
    }
    var data = dataParts.join(‘&‘);
    request.open(‘POST‘,whichform.getAttribute(‘action‘),true);
    request.setRequestHeader(‘Content-type‘,‘application/x-www-form-urlencoded‘);
    request.onreadystatechange = function(){
        if(request.readyState == ‘4‘){
            if( request.status ==200 || request.status ==0 ){
                var matches = request.responseText.match(/<article>([sS]+)</article>/);
                if( matches.length > 0){
                    thetarget.innerHTML = matches[1];//注意match[0]与match[1]
                }else{
                    thetarget.innerHTML = ‘<p>Oops,there was an error.Sorry.</p>‘;
                }
            }else{
                thetarget.innerHTML = ‘<p>‘ + request.statusText + ‘</p>‘;
            }
        }
        
    }
    request.send(data);
    return true;
}


function getHTTPObject(){
    if(typeof XMLHttpRequest == ‘undefined‘){
        try{ return new ActiveXObject(‘Msxml2.XMLHTTP.6.0‘);}
        catch(e){}
        try{ return new ActiveXObject(‘Msxml2.XMLHTTP.3.0‘);}
        catch(e){}
        try{ return new ActiveXObject(‘Msxml2.XMLHTTP‘);}
        catch(e){}
        return false;
    }else{
        return new XMLHttpRequest();
    }
}

function displayAjaxLoading(element){
    while(element.hasChildNodes()){
        element.removeChild(element.lastChild);
    }
    var content = document.createElement(‘img‘);
    content.setAttribute(‘src‘,‘images/loading.gif‘);
    content.setAttribute(‘alt‘,‘Loading^‘);
    element.appendChild(content);
    console.log(element);
}

 

以上是关于dom编程艺术章12的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript DOM编程艺术 读书笔记 第3章 DOM-文档对象模型

JavaScript DOM编程艺术(第2版)学习笔记1(1~4章)

前端开发工程师 - 03.DOM编程艺术 - 第1章.基础篇(上)

javaScript DOM编程艺术

JavaScript取消默认控件并添加新控件(DOM编程艺术第11章)

JavaScript DOM编程艺术 读书笔记 第4章 案例研究:Javascript图片库