读js DOM编程艺术总结

第一章主要介绍一些历史性问题,javascript是Netcape和sun公司合作开发的。

第二章JavaScript语法:

  1,数据类型:(弱类型)字符串,数值,布尔值(只有true和false,不是字符串)数组,对象

  2,函数:

  3,对象:(属性和方法),包括内建对象,自定义对象还有浏览器提供的预定义的宿主对象(Form,Image,Element)

第三章DOM:

  1,D(document)O(object)M(model)文档对象模型

  2,节点分为,元素节点,文本节点,属性节点。

  3,获取元素方法:getElementById(id),getElementsByTagName(tag),getElementsByClassName(class)

  一般浏览器不支持getElementsByClassName,自定义函数(1)。

  4,获取和设置属性:getAttribute(attribute),setAttribute(“attribute”,“value”)使用setAttribute做出的修改并不会改变页面的源代码

第四五六章图片库实例

  1,childNodes属性用来获取任何一个元素的所有子元素

  2,node.nodeType属性用来获取节点的属性,其中元素节点属性值1,属性节点属性值2,文本节点属性值3.

  3,node.nodeValue属性用来得到一个节点的值

  4,node.firstChild,node.lastChild属性返回父节点的第一个和最后一个子元素

  5,为了保证可访问性,要求做到平稳退化,分离出javascript,向后兼容,性能考虑

第七章动态创建标记

  1,doument.write()直接将字符串插入到文档里,不推荐使用

  2,innerHTML 用来读写给定元素里的HTML内容,包括标签名一同。不推荐使用

  3,doucment.createElement() 创建新的元素节点

  4,document.createTextNode() 创建新的文本节点,一般附加到元素节点后面

  5,appendChild(),用法为parent.appendChild(child)

  6,parentElement.insertBefore(newElement,targetElement) 在已知元素前面添加新的元素,不存在insertAfter()函数需要自己构建

  7,parentNode,返回父亲节点

  8,nextSibing,返回下一个兄弟节点

  9,Ajax主要优势就是对页面的请求以异步的方式发送到服务器,做到只更新页面中的一小部分,核心技术是XMLHttpRequest对象,包括getHTTPObject.js和  getNewContent.js两个脚本,readyState的属性值有0表示未初始化,1表示正在加载,2表示加载完毕,3表示正在交互,4表示完成

第八章充实文档的内容

  1,给文档创建缩略语函数displayAbbrreviations

  abbr标签显示缩略语,title属性给出全名

  2,给文档的文献来源连接表displayCitations

  blockquote标签块引用,cite属性给一个来源URL地址

  3,给文档显示快捷键清单displayAccesskeys

  accesskey属性把一个元素(链接)与键盘上的某个特定按键关联一起,1对应返回到本网站主页,2对应后退到前一页面,4打开本网站的搜索表单,9对应本网   站联系方法,0对应查看本网站的快捷键清单

第九章CSS-DOM

  1,结构层(HTML),表示层(css),行为层(Javascript) 

  2,Style属性是一个对象,只能返回内嵌样式,设置样式必须使用引号,是一个字符串

  3,className属性,自定义addClass函数

第十章用javascript实现动画

  1,setTimeout(“function”,interval)能够让某函数在经过一段预定时间(毫秒为单位)之后才开始执行

  clearTimeout(variable)清除时间函数,variable保存着某个setTimeout函数调用返回值的变量

  2,parseInt(),获取字符串中的数字

  3,css中overflow属性用来处理一个元素的尺寸超出其容器尺寸的情况,visible表示不裁剪溢出的内容,hidden隐藏溢出的内容,scroll隐藏但显示一个进度   条,auto溢出时显示滚动条,不溢出时不显示

  4,moveElement函数实例

第十一章HTML5简介

第十二章javascript实例

  1,使用Modernizr库,包含在header标签中

  2,多个css文件导入到一个基本的样式表中更方便@import url(layout.css);

  3,页面突出显示函数highlightPage函数,为每个页面的body添加不用的id

  4,内部导航showSection函数

  5,图片库函数showPic函数

  6,label标签,一般用于输入框前的文本提示,当点击label标签中的文本时,关联的表单字段就会获得焦点,for属性同之后输入框中的id,自定义函数

  7,form对象 ,可以用form.element.length返回表单中的包含的表单元素个数,childNodes返回所有子节点

  8,HTML5中支持placeholder属性,对于不支持此属性的浏览器自定义函数

  9,表单验证函数

  10,提交表单应用到Ajax技术,

附录el_1:按类名查找方法

function getElementsByClassName(node,classname){
  if(node.getElementsByClassName){
    return node.getElementsByClassName(classname);
  }else{
    var results = new Array();
    var elems = node.getElementsByTagName("*");
    for(var i=0;i<elems.length;i++){
      if(elems[i].className.indexOf(classname) != -1){
        results[results.length] = elems[i];
      }
    }
  return results;
  }
}
el_2:加载函数
addLoadEvent(func){
  var oldonload = window.onload;
  if(typeOf window.onload != ‘function‘){
    window.onload = func;
  }else{
    window.onload = function(){
      oldonload();
      func();
    }
  }
}
el_3:元素后面插入元素方法
function insertAfter(newElement,targetElement){
  var parent = targetElement.parentNode;
  if(parent.lastChild == targetElement){
    parent.appendChild(newElement);
  }else{
    parent.insertBefore(newElement,targetElement.nextSibling);
  }
}
el_4:Ajax对象
function getHTTPObject(){
  if(typeof XMLHttpRequest == "unfined")
  XMLHttpRequest = function(){
    try{ return new ActiveXObject("Msxml12.XMLHTTP.6.0");}
      catch(e){}
    try{ return new ActiveXobject("Msxml12.XMLHTTP.3.0");}
      catch(e){}
    try{ return new ActiveXobject("Msxm12.XMLHTTP");}
      catch(e){}
    return false;
  }
  return new XMLHttpRequest();
}
el_5:Ajax对象
function getNewContent(){
  var request = getHTTPObject();
  if(request){
    request.open("GET","example.txt",true);
    request.onreadystatechange = function(){
      if(request.readyState == 4){
        var para = document.createElement("p");
        var txt = document.createTextNode(request.responseText);
        para.appendChild(txt);
        document.getElementById(‘new‘).appendChild(para);
      }
    };
    request.send(null);
  }else{
  alert(‘sorry,your browser doesn\‘t support XMLHttpRequest‘);
  }
}
el_6:文档中添加缩略语列表
function displayAbbreviations(){
  if(!document.getElementsByTagName) return false;
  if(!document.createElement) return false;
  if(!document.createTextNode) return false;
  var abbreviations = document.getElementsByTagName("abbr");
  if(abbreviations.length < 1) return false;
  var defs = new Array();
  for(var i=0;i<abbreviations.length;i++){
    var current_abbr = abbreviations[i];
    if(current_abrr.ChildNodes.length < 1) continue;
    var definition = current_abbr.getAttribute("title");
    var key = current_abbr.lastChild.nodeVlue;
    defs[key] = definition;
  }
  var dlist = document.createElement("dl");
  for(key in defs){
    definition = defs[key];
    var dtitle = document.createElement("dt");
    var dtitle_text = document.createTextNode(key);
    dtitle.appendChild(dtitle_text);
    var ddesc = document.createElement("dd");
    var ddesc_text = document.createElement(definition);
    ddesc.appendChild(ddesc_text);
    dlist.appendChild(dtitle);
    dlist.appendChild(ddesc);
  }
  if(dlist.childNodes.length < 1) return false;
  var header = document.createElement("h2");
  var header_text = document.createTextNode("abbreviations");
  header.appendChild(header_text);
  document.body.appendChild(header);
  document.body.appendChild(dlist);
}
el_7:文档中添加文献来源链接
function displayCitations(){
  if(!document.getElementsByTagName) return false;
  if(!document.createElement) return false;
  if(!document.createTextNode) return false;
  var quotes = document.getElementsByTagName("blockquote");
  for(var i=0;i<quotes.length;i++){
    if(!quotes[i].getAttribute("cite")) continue;
    var url = quotes[i].getAttribute("cite");
    var quoteChildren = quotes[i].getElementsByTagName("*");
    if(quoteChildren.length < 1) continue;
    var elem = quoteChildren[quoteChildren.length - 1];
    var link = document.createElement("a");
    var link_text = document.createTextNode("source");
    link.appendChild(link_text);
    link.setAttribute("href",url);
    var superscript = document.cretaeElement("sup");
    superscript.appendChild(link);
    elem.appendChild(superscript);
  }
}
el_8:文档中添加快捷键函数
function displayAccesskeys(){
  if(!document.getElementsByTagName) return false;
  if(!document.createElement) return false;
  if(!document.createTextNode) return false;
  var links = document.getElementsByTagName("a");
  var skeys = new Array();
  for(var i=0;i<links.length;i++){
    var current_link = links[i];
    if(!current_link.getAttribute("accesskey")) continue;
    var key = current_link.getAttribute("accesskey");
    var text = current_link.lastChild.nodeValue;
    akey[key] = text;
  }
  var list = document.createElement("ul");
  for(key in akey){
    var text = akey[key];
    var str = key + ":" + text;
    var item = document.createElement("li");
    var item_text = document.createTextNode(str);
    item.appendChild(item_text);
    list.appendChild(item);
  }
  var header = document.createElement("h3");
  var header_text = document.createTextNode("Accesskeys");
  header.appendChild(header_text);
  document.body.appendChild(header);
  document.body.appendChild(list);
}
el_9:自定义addClass函数
function addClass(element,value){
  if(!element.className){
    element.className = value;
  }else{
    newClassName = element.className;
    newClassName += " ";
    newClassName += value;
    element.className = newClassName;  
  }
}
el_10:移动动画函数
function moveElement(elementID,final_x,final_y,interval){
  if(!document.getElementById) return false;
  if(!document.getElementById(elementID)) return false;
  var elem = document.getElementById(elementID);
  if(elem.movement){
    clearTimeout(elem.movement);
  }
  if(!elem.style.left){
    elem.style.left = "0px";
  }
  if(!elem.style.top){
    elem.style.top = "0px";
  }
  var xops = parseInt(elem.style.left);
  var ypos = parseInt(elem.style.top);
  var dist = 0;
  if(xpos == final_x && ypos == final_y){
  return true;
  }
  if(xops < final_x){
  dist = Math.ceil((final_x - xps) / 10);
  xpos = final_x - xpos;
  }
  if(xpos > final_x){
  dist = Math.ceil((xpos - final_x) / 10);
  xpos = xpos - final_x;
  }
  if(ypos < final_y){
  dist = Math.ceil((final_y - ypos) / 10);
  ypos = final_y - ypos;
  }
  if(ypos > final_y){
  dist = Math.ceil((ypos - fianl_y) /10 );
  ypos = ypos - fianl_y;
  }
  elem.style.left = xpos + "px";
  elem.style.top = ypos + "px";
  var repeat = "moveElement(‘"+elementID+"‘,"+final_x+","+final_y+","+interval+")";
  elem.movement = setTiemout(repeat,interval);
}
el_11:页面突出显示函数
function highlightPage(href){
  if(!document.getElementsByTagName) return false;
  if(!document.getElementById) return false;  
  var headers = document.getElementsByTagName(‘header’);
  if(headers.length == 0) return false;
  var navs = header[0].getElemntsByTagName("nav");
  if(navs.length == 0) return false;
  var links = navs[0].getElementsByTagName("a");
  var linkurl;
  for(var i=0;i<links.length;i++){
    linkurl = links[i].getAttribute(‘href‘);
    if(window.location.href.indexOf(linkurl) != -1){
      links[i].className = ‘here‘;
      var linktext = links[i].lastChild.nodeValue.toLowerCase();
      document.body.setAttribute("id",linktext);
  }
}
}
el_12:内部导航函数
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";
    }
  }
}
function prepareInternalnav(){
  if(!document.getElementsByTagName) return false;
  if(!document.getElementById) return false;
  var articles = document.getElementsByTagName("article");
  if(articles.length == 0) return false;
  var navs = articles[0].getElementsByTagName("nav");
  if(navs.length == 0) return false;  
  var nav = navs[0];
  var links = nav.getElementsByTagName("a");
  for(var i=0;i<links.length;i++){
    var sectionId = links[i].getAttribute("href").split("#")[1];
    if(!document.getElementById(sectionId)) continue;
    document.getElementById(sectionId).style.display = ‘none‘;
    links[i].destination = sectionId;
    links[i].onclick = function(){
      showSection(this.destination);
      return false;
    }
  }  
}
el_13:图片展示函数showPic
function showPic(whichpic){
  if(!document.getElementById("placeholder")) return false;
  var source = whichpic.getAttribute("href");
  var placeholder = document.getElementById("placeholder");
  placeholder.setAttribute("src","source");
  if(!document.getElementById("description")) return false;
  if(whichpic.getAttribute("title")){
    var text = whichpic.getAttribute("title");
  }else{
    var text = "";
  }  
  var description = document.getElementById("description");
  if(description.firstChild.nodeType == 3){
    description.firstChild.nodeValue = text;
  }
  return false;
}
function preparePlaceholder(){
  if(!document.createElement) return false;
  if(!document.createTextNode) return false;
  if(!document.getElementById) return false;
  if(!document.getElementById("imagegallery")) return false;
  var placeholder = document.createElement("img");
  placeholder.setAttribute("id","placeholder");
  placeholder.setAttribute("src","images/placeholder.jpg");
  placeholder.setAttribute("alt","my description");
  var description = document.createElement("p");
  description.setAttribute("id","description");
  var desctext = document.createTextNode("choose an image");
  description.appendChild(desctext);
  var gallery = document.getElementById("imagegallery");
  insertAfter(description,gallery);
  insertAfter(placeholder,description);
}
function prepareGallery(){
  if(!document.getElementsByTagName) return false;
  if(!document.getElementById) 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(){
      return showPic(this);
    }
  }
}
el_14:重写label标签的作用函数
function focusLabels(){
  if(!document.getElementsByTagName) return false;
  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 element = document.getElementById(id);
      element.focus();
    }
  }
}
el_15:自定义支持placeholder函数
function resetFieldas(whichform){
  if(Modernizr.input.placeholder) return;
  for(var i =0;i<whichform.elements.length;i++){  
    var element = whichform.elements[i];
    if(element.type == "submmit") continue;
    var check = element.placeholder || element.getAttrtibute("placeholder");
    if(!check) continue;
    element.onfocus = function(){  
      var text = this.placeholder || this.getAttribute(‘placeholder‘);
      if(this.value == text){
        this.className = ‘‘;
        this.valu = "";
      }
    }
    element.onblur = function(){
      if(this.value = ""){
        this.className = ‘placeholder‘;
        this.value = this.placeholder || this.getAttribute(‘placeholder‘);
      }
    }
    element.onblur();
  }
}
function prepareForms(){
  for(var i=0;i<document.forms.length;i++){
    var thisform = document.forms[i];
    resetFields(thisform);
  }
}
el_16:表单验证函数
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);
}
function validateForm(whichform){
  for(var i=0;i<whichform.elements.length;i++){
    var element = whichform.elements[i];
    if(element.required == ‘required‘){
      if(!isFilled(element)){
        alert("Please fill in the "+element.name+" field.");
        return false;
      }
    }
    if(element.type == ‘email‘){
      if(!isEmail(element)){
        alert("The "+element.name+" field must be a valid email address.");
        return false;
      }  
    }
  }
  return false;
}
function prepareForms(){
  for(var i=0;i<document.forms.length;i++){
    var thisform = document.forms[i];
    resetFields(thisform);
    thisform.onsubmit = function(){
      return validateForm(this);
    }
  }
}
el_17:提交表单函数Ajax技术
function displayAjaxLoading(element){
  while(element.hasChildNodes()){
    element.removeChild(element.lastChild);
  }
  var content = document.createElement("img");
  content.setAttribute("src","images/loading.jpg");
  content.setAttribute("alt","loading...");
  element.appendChild(content);
}
function submitFormWithAjax(whichform,thetarget){
  var request = getHTTPObject();
  if(!request){return false;}
  displayAjaxLoading(thetarget);
  var dataParts = [];
  var element;
  for(var i=0;i<whichform.elements.length;i++){
    element = whichform.elements[i];
    dataParts[i] = element.name + ‘=‘ + encodeURIComponent)(element.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 = matcher[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 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;  
    }    
  }
}

读js DOM编程艺术总结,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。