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>([\s\S]+)<\/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);
}

原文地址:https://www.cnblogs.com/linbudu/p/10354573.html

时间: 2024-10-12 15:40:08

dom编程艺术章12的相关文章

JavaScript Dom编程艺术 第6章的一个错误

今天在看JavaScript Dom编程艺术 第6章:图片库的改进版时:按照书上的代码,敲出来运行,确怎么也不能显示出正确的结果.加进去断点,调试,发现:prepareGallery 函数根本没被调用,而prepareGallery函数是绑定到window.onLoad事件上的,于是仔细检查书上代码,发现,window.onLoad = prepareGallery;后边少加了个括号.加上括号之后,结果正确.改正后的代码如下: 1 function addLoadEvent(func){ 2 v

JavaScript DOM编程艺术第一章:JavaScript简史

本系列的博客是由本人在阅读<JavaScript DOM编程艺术>一书过程中做的总结.前面的偏理论部分都是书中原话,觉得有必要记录下来,方便自己翻阅,也希望能为读到本博客的人提供一些帮助,所以 如果您也看过这本书,希望不要喷小的"抄袭",其实我也懒得敲这些文字也想简单粗暴地上代码,但是只有实践没有理论不容易自己理解,为避免误导,该"抄"的地方还是要"抄"的,哈哈~~ 一.JavaScript的起源 JavaScript是Netscap

JavaScript对于DOM的常见操作——《JavaScript DOM编程艺术》读书总结

读完一本书一定要将收获进行整理沉淀,不然相当于白读.<JavaScript DOM编程艺术>的确是一本JavaScript好的入门书,简短精炼,现在就用一篇文章对本书中的一些知识要点进行总结. 首先要明白的一件事就是什么是DOM.DOM即文档对象模型(Document Object Model),document指的就是网页文档,而Object,在JavaScript中共有三种对象,分别是用户定义对象.内建对象(Array.Date和Math等)以及宿主对象(由浏览器提供的对象).而Model

《JavaScript dom 编程艺术》 placeholder占位符IE8兼容办法。

在<JavaScript dom 编程艺术>第11章学来的. 相对于用JavaScript替换文本框的提示语句 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 <script> 7 window.onload = funct

《DOM编程艺术》读书笔记&lt;概述&gt;

作为一名前端开发工程师,学习的过程中总少不了各种各样的书籍,作为新手如何在众多书籍中选到适合自己的呢,我们今天先来谈谈<DOM编程艺术>这本书. 其实呢大部分书都是好书,就像LOL中大部分英雄都很厉害,只有不强悍的召唤师.先了解一本书,然后认真的读下去你一定会有所收获的.在网上搜索书单时,你大概率会看到标题中这本书,但是又会看到褒贬不一的评论,那么这本书到底适不适合入门阅读呢,且听我慢慢道来. 读完这本书的第一感觉就是这本书里面好多内容已经过时了,比如里面大量的 js 对浏览器兼容性的检查,会

JavaScript DOM编程艺术 读书笔记

3 DOM DOM分别指document,object和model. DOM中包含的节点主要分为三种:元素节点.文本节点和属性节点.DOM的原子是元素节点,标签的名字就是元素的名字,元素可以包含其他的元素.没有被包含在其他元素里的唯一元素是<html>元素,它是树节点的根元素:在XHTML文档里,文本节点总是被包含在元素节点的内部.但并非所有的元素节点都包含有文本节点:属性节点用来对元素做出更具体地描述. 有3种DOM方法可获取元素节点,分别是通过元素ID.通过标签名字和通过类名字来获取. 1

js学习12-《JS DOM 编程艺术》笔记

学习了下<JS DOM 编程艺术>,做个学习总结:1.字符串中放单引号双引号:建议:字符串中放单引号,则用双引号包含字符串 1 var s1="It's my doy"; 字符串中放双引号,则用单引号包含字符串 1 var s2='He said "hi!" '; 其他使用\进行转义 2.==和====== :严格比较.不仅比较值,还比较类型== :不严格比较,转换类型一致比较 3.JS语言里对象的三种类型3.1内建对象:javascript提供的对象

《javascript dom编程艺术》笔记(一)——优雅降级、向后兼容、多个函数绑定onload函数

刚刚开始自学前端,如果不对请指正:欢迎各位技术大牛指点. 开始学习<javascript dom编程艺术>,整理一下学习到的知识.今天刚刚看到第六章,记下get到的几个知识点. 优雅降级 看到版本翻译为预留退路,刚刚看到个名词,我觉得很奇怪,以前没有听说过啊.不过看到英文注释就知道了Graceful degradation不就是优雅降级么,听说过! 书中举了个例子,点击一个链接,弹出一个窗口的方法. function popUp(WinURL){ window.open(WinURL,&quo

《javascript DOM 编程艺术》学习笔记(一)

书籍已经看完了前六章的内容,有了一定的编程基础后觉得本书内容相对来说过于简单,应该是完全针对于初学者的(或者如作者所说是写个Web设计师的),作者在表述一个问题,一句代码都解释得非常啰嗦与重复,不过从书中学习到更多的,也是作者想让读者体会的是让大家理解DOM脚本编程技术背后的思路和原则,作者特别以早期Javascript的滥用来强调Web的规范与标准,这一点是非常值得学习的,也是一个程序员的基本素养. 截止到第六章,将所学到的知识点归纳如下: 1.基本语法:与php一样是弱类型语言,虽然功能强大