首页 > 网站 > WEB开发 > 正文

《JavaScript修炼之道》读书笔记

2024-04-27 14:15:47
字体:
来源:转载
供稿:网友

javaScript修炼之道》读书笔记

1、参考书目

入门:《Javascript DOM编程艺术》第二版

进阶:《JavaScript高级程序设计》第二版、《JavaScript编程精粹》

《JavaScript权威指南》

2、引言

Node.js是CommonJS的一个部分实现

本书代码下载:

http://github.com/tdd/PRagmatic-javascript

https://github.com/tdd/pragmatic-javascript/archive/master.zip

http://media.pragprog.com/titles/pg_js/code/pg_js-code.tgz

介绍的框架包括:Prototype、jQuery、MooTools、YUI、Dojo、ExtJS

3、利用事件委托

  • 优先使用事件委托
  • 元素共享同一个行为,最好在DOM高层次监听事件,这样可以节省内存和CPU时间

dom/delegation.html

<ul id="items">  <!-- We will insert togglers in each LI using JS -->  <li><div><p>Data 1</p><p>Data 2</p></div></li>  <li><div><p>Data 1</p><p>Data 2</p></div></li>  <li><div><p>Data 1</p><p>Data 2</p></div></li>  <!-- Potentially lots more elements here… --></ul>

dom/delegation.js(Prototype)

document.observe('dom:loaded', function() {  $('items').observe('click', function(e) {     var trigger = e.findElement('a.toggler');     if (!trigger) return;    e.stop();    var content = trigger.up('p').next('div');    if (!content) return;    content.toggle();    trigger.update(content.visible() ? 'Close' : 'Open');    trigger.blur();  });  $('items').select('li').each(function(item) {    item.insert({ top: '<p><a class="toggler" href="#">Open</a></p>' });    item.down('div').hide();  });});

4、模拟后台处理

  • 利用HTML5的Web Workers实现多线程
  • 分解成多个小任务,利用setTimerout和clearTimeout模拟后台处理
var handle = windows.setTimeout(callback, intervalInMs)window.clearTimeout(hanle);

参考https://github.com/madrobby/emile 50行小程序实现精确定时器

(function(emile, container){  var parseEl = document.createElement('div'),    props = ('backgroundColor borderBottomColor borderBottomWidth borderLeftColor borderLeftWidth '+    'borderRightColor borderRightWidth borderSpacing borderTopColor borderTopWidth bottom color fontSize '+    'fontWeight height left letterSpacing lineHeight marginBottom marginLeft marginRight marginTop maxHeight '+    'maxWidth minHeight minWidth opacity outlineColor outlineOffset outlineWidth paddingBottom paddingLeft '+    'paddingRight paddingTop right textIndent top width WordSpacing zIndex').split(' ');  function interpolate(source,target,pos){ return (source+(target-source)*pos).toFixed(3); }  function s(str, p, c){ return str.substr(p,c||1); }  function color(source,target,pos){    var i = 2, j, c, tmp, v = [], r = [];    while(j=3,c=arguments[i-1],i--)      if(s(c,0)=='r') { c = c.match(//d+/g); while(j--) v.push(~~c[j]); } else {        if(c.length==4) c='#'+s(c,1)+s(c,1)+s(c,2)+s(c,2)+s(c,3)+s(c,3);        while(j--) v.push(parseInt(s(c,1+j*2,2), 16)); }    while(j--) { tmp = ~~(v[j+3]+(v[j]-v[j+3])*pos); r.push(tmp<0?0:tmp>255?255:tmp); }    return 'rgb('+r.join(',')+')';  }    function parse(prop){    var p = parseFloat(prop), q = prop.replace(/^[/-/d/.]+/,'');    return isNaN(p) ? { v: q, f: color, u: ''} : { v: p, f: interpolate, u: q };  }    function normalize(style){    var CSS, rules = {}, i = props.length, v;    parseEl.innerHTML = '<div style="'+style+'"></div>';    css = parseEl.childNodes[0].style;    while(i--) if(v = css[props[i]]) rules[props[i]] = parse(v);    return rules;  }      container[emile] = function(el, style, opts, after){    el = typeof el == 'string' ? document.getElementById(el) : el;    opts = opts || {};    var target = normalize(style), comp = el.currentStyle ? el.currentStyle : getComputedStyle(el, null),      prop, current = {}, start = +new Date, dur = opts.duration||200, finish = start+dur, interval,      easing = opts.easing || function(pos){ return (-Math.cos(pos*Math.PI)/2) + 0.5; };    for(prop in target) current[prop] = parse(comp[prop]);    interval = setInterval(function(){      var time = +new Date, pos = time>finish ? 1 : (time-start)/dur;      for(prop in target)        el.style[prop] = target[prop].f(current[prop].v,target[prop].v,easing(pos)) + target[prop].u;      if(time>finish) { clearInterval(interval); opts.after && opts.after(); after && setTimeout(after,1); }    },10);  }})('emile', this);

dom/background.js

var CHUNK_INTERVAL = 25; // ms.  var running = false, progress = 0, processTimer;  function runChunk() {    window.clearTimeout(processTimer);    processTimer = null;    if (!running) return;    // Some work chunk.  Let's simulate it:    for (var i = 0; i < 10000; i += (Math.random() * 5).round())      ;    ++progress;    updateUI(); // See source archive -- just updates a progressbar    if (progress < 100) {      processTimer = window.setTimeout(runChunk, CHUNK_INTERVAL);    } else {      progress = 0, running = false;    }  }    function toggleProcessing() {    running = !running;    if (running) {      processTimer = window.setTimeout(runChunk, CHUNK_INTERVAL);    }  }

5、打造漂亮的tooltip

用CSS属性设置tooltip元素为默认隐藏,并在其内容标签上加:hover选择器来恢复显示。

但这种方式在IE6不起作用,因为IE6只允许<a>元素上有:hover。只能手动编写脚本,响应mouSEOver和mouseout。

作者推荐Prototype的Prototip2库http://www.nickstakenburg.com/projects/prototip2/

4{5OB7)DWK}Y6YWLGWM3CCA

ui/tooltips/index.html

<li tabindex="1">    <span class="name">Capacity: 1.5 TB</span>    <div class="tooltip" >      <p><strong>1.5 Terabyte = 1,536 Gigabytes</strong></p>      <p>Enough for 50,000 songs, 1,000 DivX movies, 100,000        high-definition photos, hundreds of iDVD projects and        plenty of backup space left.</p>    </div>  </li>

ui/tooltips/tooltips.css

#files li { position: relative; }#files li .tooltip {  position: absolute; top: 8px; left: 120px; width: 24em;  z-index: 1; display: none;  /* IE6 doesn't know li:hover, so we need to toggle via JS,     therefore avoiding in-rule display: none */  _display: block;  border: 1px solid gray;   background: #fffdc3 url(bg_tooltip.png) top left repeat-x;}#files li:hover .tooltip,#files li:focus .tooltip { display: block; }

ui/tooltips/tooltips.js

function toggle(reveal, e) {    var trigger = e.findElement('li'),      tooltip = trigger && trigger.down('.tooltip');    if (!tooltip) return;    tooltip[reveal ? 'show' : 'hide']();  }    document.observe('dom:loaded', function() {    var isIE6 = Prototype.Browser.IE &&      undefined === document.body.style.maxHeight;    if (!isIE6) return;    var files = $('files'), tooltips = files && files.select('.tooltip');    if (!files || 0 == tooltips.length) return;    tooltips.invoke('hide');    files.observe('mouseover', toggle.curry(true)).      observe('mouseout', toggle.curry(false));  });

6、友好的弹窗

用<a>链接到要弹出的内容(href=,target=”_blank”),然后在链接上挂上JavaScript代码。这样可以解决禁止弹窗、屏幕阅读器(视觉障碍者使用)、搜索引擎的访问问题。

ui/popups/index.html

<p>  The great thing about <a class="popup" target="_blank"  href="http://pragprog.com/titles/pg_js">Pocket Guide to JavaScript</a>  is that it focuses on a bunch of specific, useful tasks.</p>

ui/popus/popus.js

var POPUP_FEATURES = 'status=yes,resizable=yes,scrollbars=yes,' +     'width=800,height=500,left=100,top=100';    function hookPopupLink(e) {    var trigger = e.findElement('a.popup');    if (!trigger) return;    e.stop(); trigger.blur();    var wndName = trigger.readAttribute('target') ||      ('wnd' + trigger.identify());    window.open(trigger.href, wndName, POPUP_FEATURES).focus();  }    document.observe('click', hookPopupLink);

7、光箱特效

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表