DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

时间:2020-12-25 19:26:15

1. childNodes  nodeValue

<p id="p1">hello p!</p>

alert(document.getElementById("p1").childNodes[0].nodeValue);

2. firstChild lastChild

childNodes[0] 等价于 firstChild   (node.childNodes[0] == node.firstChild)

node.childNodes[node.childNodes.length-1] 等价于 node.lastChild

3. nodeValue 赋值

  var description = document.getElementById("p1");

description.firstChild.nodeValue = text;

4. nodeType

nodeType共有12中可取值,只有三种具有实用价值

·元素节点 的nodeType值为1

属性节点的 nodeType值为2

文本节点的nodeType值为3

5. window.open(url, windowName, features)

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

<a href="javascript:popUp('http://www.baidu.com');">hehehehe</a>//伪协议

<script>

function popUp(winURL){
    window.open(winURL, "mywindow", "width=110, height=222");
}

6. 平稳退化

<a href="http://www.baidu.com" onClick="popUp(this.href);return false;">hehehehe</a>

7. 分离javascript

var links = document.getElementsByTagName("a");

for(var i=0; i<links.length; i++){

  if(links[i].getAttribute("class")==="popup"){

  links[i].onclick = function(){

      popUp(this.getAttribute("href"));

      return false;

}  

  }

}

</script>

8. document对象是wndow对象的一个属性,当window对象触发onload事件时,document对象已经存在

9.对象检测

if(!document.getElementsByTagName)return false;

10 合并和放置脚本 浏览器同时下载文件的数量有限

11 压缩脚本 去掉注释 空格等

脚本文件应该有两个版本 一是工作副本,可以修改代码并添加注释;一是精简副本(文件名中通常加上min example.min.js),用于放在站点上

代码压缩工具 谷歌Closure compiler

12. window.onload绑定事件

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

改进;

function addLoadEvent(func){
    var oldonload = window.onload;
    if(typeof oldonload !='function'){
        window.onload = func;
    }else{
        window.onload = function(){
            oldonload();
            func();
        }
    }
}

然后调用

addLoadEvent(firstFunction);

addLoadEvent(secondFunction);

13. nodeName 该属性总是返回一个大写字母的值

<img src="data:image/a.jpg"/ id="mypic">

var mypic = document.getElementById("mypic");

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

14. onkeypress键盘事件

可以使用 links[i].onkeypress = links[i].onclick;把onclick事件的所有功能赋给onkeypress

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

15 innerHTML 属性无细节可言, 要想获得细节 需要用dom的方法和属性; 类似于document.write, innerHTML也是HTML专有属性

testdiv.innerHTML = "<p>i am <em>a </em>teacher</p>";

16 dom方法

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

17. createElement 只能创建元素节点

var para = document.createElement("p");

alert(para.nodeName);

alert(para.nodeType);

18 appendChild

var testdiv = document.getElementById("testdiv");

testdiv.appendChild(para);

19. createTextNode 创建文本节点

var text = document.createTextNode("hello js");

para.appendChild(text);

20. DOM insertBefore()

parentElement.insertBefore(newElement, targetElement);

我们不必搞清楚父元素是哪个  targetElement元素的parentNode属性就是它

21 insertAfter

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

22. Ajax XMLHttpRequest

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

创建XMLHttpRequest对象

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

XMLHttpRequest open()方法

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

访问服务器返回的数据

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

注意

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

23 Hijax 渐进增强的使用ajax

正常的登录使用form表单触发submit事件, 只要使用onsubmit事件处理函数捕获该事件,就可以取消他的默认操作(提交整个页面)

然后通过XMLHttpRequest对象向服务器发送请求。

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

24. 两点原则

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

25. 缩略语标签abbr

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

26. DOCTYPE 标准模式

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

27. 从abbr标签读取title并按照定义列表(dl)方式展示

function displayAbbreviations(){
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];
var description = current_abbr.getAttribute("title");
var key = current_abbr.lastChild.nodeValue;
defs[key] = description; }
var dlist = document.createElement("dl");
for(key in defs){
var dtitle = document.createElement("dt");
var dtitle_text = document.createTextNode(key);
dtitle.appendChild(dtitle_text); var ddesc = document.createElement("dd");
var ddesc_text = document.createTextNode(defs[key]);
ddesc.appendChild(ddesc_text); dlist.appendChild(dtitle);
dlist.appendChild(ddesc); }
var header = document.createElement("h2");
var header_text = document.createTextNode("Abbreviations");
header.appendChild(header_text);
document.body.appendChild(header);
document.body.appendChild(dlist);
}

28. CSS DOM要求用驼峰命名

element.style.font-family报错 应使用 element.style.fontFamily

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

29.  获取下一个元素节点

function getNextElement(node){
if(node.nodeType==1){
return node;
}
if(node.nextSibling){
return getNextElement(node.nextSibling);
}
return null;
}

30. 表格奇数偶数行斑马色

function stripTables(){
var tables = document.getElementsByTagName("table");
var odd, rows;
for(var i=0; i<tables.length; i++){
odd = false;
rows = tables[i].getElementsByTagName("tr");
for(var j=0; j<rows.length; j++){
if(odd==true){
rows[j].style.backgroundColor = "#ffc";
odd = false;
}else{
odd = true;
}
}
}
}

31. css :hover伪类

如果只想鼠标悬停在链接、表格行上时改变颜色、字体等,可以使用css :hover

<head>
<style>
tr:hover{
font-weight : bold;
}
</style>
</head>

使用js同样实现

function highlightRows(){
var rows = document.getElementsByTagName("tr");
for(var i=0; i<rows.length; i++){
rows[i].onmouseover = function(){
this.style.fontWeight = "bold";
};
rows[i].onmouseout = function(){
this.style.fontWeight = "normal";
}
}
}

32. 可以通过js给标签赋予某class值 再在css中对该class定义样式 这样在更新时就可以避免修改js

element.className = "intro";

css中

.intro{

  font-weight : bold;

font-size : 1.4em;

}

这个技巧有一个不足 element标签原来有一些样式时 原样式会被覆盖 添加addClass函数处理

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

javascript现在更新的是className属性,根本没碰style,分离更彻底

33. setTimeout函数能够让某个函数在经过一个预定时间之后运行

var variable;

variable = setTimeout('function', interval);

clearTimeout函数能够取消setTimeout中准备执行的函数

clearTimeout(variable);

34. parseInt(string) 返回一个数值

parseInt("39 step")将返回数值39  parseInt("50px")将返回50

parseFloat(string) 将返回浮点数

35. 图片在页面内定时更新位置 实现动画效果

<!DOCTYPE html>
<html en="lang">
<head>
<meta charset="utf-8"/>
</head>
<body>
<img id="mypic" src="hellonodejs.png"/>
<script src="animation.js"></script>
</body>
</html>
---------animation.js---------
function moveMessage(){ var elem = document.getElementById("mypic");
var xpos = parseInt(elem.style.left);// pos.left
var ypos = parseInt(elem.style.top);//style.top
if(xpos==300 && ypos==300)return true;
if(xpos<300) xpos++;
if(xpos>300) xpos--;
if(ypos<300) ypos++;
if(ypos>300) ypos--;
elem.style.left = xpos + "px";
elem.style.top = ypos + "px";
setTimeout(moveMessage, 10);
}
function initPos(){ var elem = document.getElementById("mypic");
//elem.className = "newstyle";
elem.style.position = "relative";
elem.style.left = "600px";
elem.style.top = "200px";
}
function addLoadEvent(func){
var oldonload = window.onload;
if(typeof window.onload!='function'){
window.onload = func;
}else{
window.onload = function(){
oldonload();
func();
}
}
}
addLoadEvent(initPos);
addLoadEvent(moveMessage);

36. 鼠标悬停于a链接 图片切换

<!doctype html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>testAnimation</title>
<link href="b3.css" rel="stylesheet" type="text/css"/>
</head>
<body >
<ol id="olist">
<li><a href="www.baidu.com">百度</a></li>
<li><a href="www.alibaba.com">阿里</a></li>
<li><a href="www.qq.com">qq</a></li>
<li><a href="www.ibm.com">ibm</a></li>
</ol>
<div id="previewdiv">
<img src="111.jpg" id="scrollPic"/>
</div>
<script src="b3.js"></script>
</body>
</html> ------------b3.css-------------
#previewdiv{
position : absolute;
width : 280px;
height : 210px;
overflow : hidden;
} ----------------b3.js---------------------
function moveMessage(elementID, final_x, final_y, interval){
var elem = document.getElementById(elementID);
var xpos = parseInt(elem.style.left);
var ypos = parseInt(elem.style.top);
if(xpos==final_x && ypos==final_y) return true;
if(xpos<final_x) xpos++;
if(xpos>final_x) xpos--;
if(ypos<final_y) ypos++;
if(ypos>final_y) ypos--;
elem.style.left = xpos + "px";
elem.style.top = ypos + "px";
var repeat = "moveMessage('"+elementID+"', '"+final_x+"', '"+final_y+"', '"+interval+"')";
movement = setTimeout(repeat, interval);
} function positionMessage(){ var elem = document.getElementById("scrollPic");
elem.style.position = "relative";
elem.style.left = "0px";
elem.style.top = "0px";
var olist = document.getElementById("olist");
var links = olist.getElementsByTagName("a");
links[1].onmouseover = function(){moveMessage("scrollPic", -280, 0, 10)};
links[2].onmouseover = function(){moveMessage("scrollPic", -560, 0, 10)};
links[3].onmouseover = function(){moveMessage("scrollPic", -840, 0, 10)}; }
function addLoadEvent(func){
var oldonload = window.onload;
if(typeof window.onload!='function'){
window.onload = func;
}else{
window.onload = function(){
oldonload();
func();
}
}
}
addLoadEvent(positionMessage);

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

解决办法

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

代码

function moveMessage(elementID, final_x, final_y, interval){
var elem = document.getElementById(elementID);
if(elem.movement){
clearTimeout(elem.movement);
}
var xpos = parseInt(elem.style.left);
var ypos = parseInt(elem.style.top);
if(xpos==final_x && ypos==final_y) return true;
if(xpos<final_x) xpos++;
if(xpos>final_x) xpos--;
if(ypos<final_y) ypos++;
if(ypos>final_y) ypos--;
elem.style.left = xpos + "px";
elem.style.top = ypos + "px";
var repeat = "moveMessage('"+elementID+"', '"+final_x+"', '"+final_y+"', '"+interval+"')";
elem.movement = setTimeout(repeat, interval);
}

优化效果

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

借助js函数

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

代码

var dist = 0;
if(xpos < final_x) {
dist = Math.ceil((final_x-xpos)/10);
xpos += dist;
};
if(xpos > final_x) {
dist = Math.ceil((xpos-final_x)/10);
xpos -= dist;
};
if(ypos < final_y) {
dist = Math.ceil((final_y - ypos)/10);
ypos += dist;
};
if(ypos > final_y) {
dist = Math.ceil((ypos - final_y)/10);
ypos -= dist;
};

37. 添加安全检查

这里elem的left样式属性和top样式属性可能不存在

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

if(!elem.style.left){
elem.style.left = 0px;
}
if(!elem.style.top){
elem.style.top = 0px;

}

整理后的moveElement函数

function moveMessage(elementID, final_x, final_y, interval){
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 xpos = parseInt(elem.style.left);
var ypos = parseInt(elem.style.top);
if(xpos==final_x && ypos==final_y) return true;
var dist = 0;
if(xpos < final_x) {
dist = Math.ceil((final_x-xpos)/10);
xpos += dist;
};
if(xpos > final_x) {
dist = Math.ceil((xpos-final_x)/10);
xpos -= dist;
};
if(ypos < final_y) {
dist = Math.ceil((final_y - ypos)/10);
ypos += dist;
};
if(ypos > final_y) {
dist = Math.ceil((ypos - final_y)/10);
ypos -= dist;
};
elem.style.left = xpos + "px";
elem.style.top = ypos + "px";
var repeat = "moveMessage('"+elementID+"', '"+final_x+"', '"+final_y+"', '"+interval+"')";
elem.movement = setTimeout(repeat, interval);
}

如果用户禁用了javascript, 那么上面展示动画的div和img就显得无用 所以应该动态追加这两个标签

用到document.createElement  insertAfter(自己实现)

38. html5

http://modernizr.cn/

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

39. html5 canvas 图片灰度处理例子

----grayscale.html------
<!DOCTYPE html>
<html en="lang">
<head>
<meta charset="utf-8"/>
<script src="modernizr.js"></script>
</head>
<body>
<img src="111.png" id="pic_test" alt="ta shi ta" title="wo shi title"/><!-->
<script src="grayscale.js"></script>
</body>
</html> ----------grayscale.js-------------
function convertToGS(img){
//如果浏览器不支持<canvas>就返回
if(!Modernizr.canvas) return;
//存储原始的彩色版
img.color = img.src;
//创建灰度版
img.grayscale = createGSCanvas(img);
//在mouseover/out事件发生时切换图片
img.onmouseover = function(){
this.src = this.color;
//this.src = this.grayscale;
}
img.onmouseout = function(){
this.src = this.grayscale;
//this.src = this.color;
}
img.onmouseout();
} function createGSCanvas(img){
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height; var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
//注意 getImageData 只能操作与脚本位于同一个域中的图片
var c = ctx.getImageData(0, 0, img.width, img.height);
for(i=0; i<c.height; i++){//var
for(j=0; j<c.width; j++){//var
var x = (i*4)*c.width + (j*4);
var r = c.data[x];
var g = c.data[x+1];
var b = c.data[x+2];
c.data[x] = c.data[x+1] = c.data[x+2] = (r+g+b)/3;
}
} ctx.putImageData(c, 0, 0, 0, 0, c.width, c.height);
return canvas.toDataURL();
}
window.onload = function(){
convertToGS(document.getElementById("pic_test"));
}

40. html5 视频 video标签

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

41. 使用video标签例子

movie.html

<!DOCTYPE html>
<html en="lang">
<head>
<meta charset="utf-8"/>
<title>My Video</title>
<link rel="stylesheet" href="styles/player.css" />
<script src="//cdn.bootcss.com/html5media/1.1.8/html5media.js"></script>
</head>
<body>
<div class="video-wrapper">
<video id="movie" controls>
<source src="movie2.mp4"/>
<source src="movie.webm" type='video/webm; codecs="vp8, vorbis"' />
<source src="movie.ogv" type='video/ogg; codecs="theora, vorbis"' />
<p>Download movie as
<a href="movie2.mp4">MP4</a>,
<a href="movie.webm">WEBM</a>,
or <a href="movie.ogv">OGG.</a>
</p>
</video>
</div>
<script src="scripts/player.js"></script>
</body>
</html>

player.js

function createVideoControls(){
var vids = document.getElementsByTagName("video");
for(var i=0; i<vids.length; i++){
addControls(vids[i]);
}
} function addControls(vid){
vid.removeAttribute("controls"); vid.height = vid.videoHeight;
vid.width = vid.videoWidth;
vid.parentNode.style.height = vid.videoHeight + "px";
vid.parentNode.style.width = vid.videoWidth + "px"; var controls = document.createElement('div');
controls.setAttribute('class', 'controls'); var play = document.createElement('button');
play.setAttribute('title', 'Play');
play.innerHTML = '►'; controls.appendChild(play); vid.parentNode.insertBefore(controls, vid);
play.onclick = function(){
if(vid.ended){
vid.currentTime = 0;
}
if(vid.paused){
vid.play();
}else{
vid.pause();
}
}; vid.addEventListener('play', function(){
play.innerHTML = '▐▐';
play.setAttribute('paused', true);
}, false);
vid.addEventListener('pause', function(){
play.removeAttribute('paused');
play.innerHTML = '►';
}, false);
vid.addEventListener('ended', function(){
vid.pause();
}, false);
} window.onload = function(){
createVideoControls();
}

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

player.css

.video-wrapper{
overflow : hidden;
} .video-wrapper .controls{
position : absolute;
height : 30px;
width : 30px;
margin : auto;
background : rgba(0,0,0,0.5);
} .video-wrapper button{
display : block;
width : 100%;
height : 100%;
border :;
cursor : pointer;
font-size : 17px;
color : #fff;
background : transparent;
} .video-wrapper button[paused]{
font-size : 12px;
}

42. 新的输入控件类型

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

43. 新的属性

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

44. 标签的兼容问题

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

45. html5的其他特性

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

46. label 标签

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

47. form 对象

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

48. placeholder 属性处理

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;
element.onfocus = function(){
var text = this.placeholder || this.getAttribute('placeholder');
if(this.value == text){
this.className = '';
this.value = '';
}
}
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);
}
}

49. required属性

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

50. javascript字符串编码

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

51. 正则表达式

提取article标签对中的内容

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

注意

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

解释

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

52. 压缩代码

工具 JavaScript Minifier

压缩后可命名为global.min.js   和原来的global.js一并放在scripts文件夹下

53. 内容分发网络 CDN

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

cdn不够用

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

54. 语法

54.1 连缀

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

54.2 迭代

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

55. 选择元素

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

55.1 css选择器

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

55.2. css2.1属性选择器

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

55.3 子选择器或同辈选择器

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

55.4 伪类和伪元素选择器

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

56.  库所提供的专有选择器

如jquery提供的$('tag:odd') 和$('tag:even')用于选择奇数和偶数元素

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

其他

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

表单

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

57.回调函数

jquery的表达式选择器 filter方法

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

58.操作dom

58.1 生成内容

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

58.2 jquery的templates模板插件

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

58.3操作内容

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

59 处理事件

59.1 加载事件

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

jquery加载

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

59.2 其他事件

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

60. jquery与ajax

60.1

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

状态值是 success  error  notmodified

例子

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

60.2 load方法

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

60.3 周期性的保存

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

61.  动画和效果

改写之前的moveElement()方法

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

animate函数

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

61.2 组合动画

DOM Scripting -- Web Design with JavaScript and the Document Object Model 第2版 读书笔记

61.3 注意可访问性