03_事件

来源:互联网 发布:盗取商业数据 编辑:程序博客网 时间:2024/05/16 11:12

3.1 在页面加载后执行任务

3.1.1 代码执行的时机选择

$(document).ready()和window.onload的区别

两者貌似相同,但是在一个有很多图片的页面上,

前者在所有图片没有都下载下的情况下就可以操作页面,

而后者需要在页面所有元素准备就绪才能操作页面。

3.1.2 基于一个页面执行多个脚本

window.onload = doStuff;

window.onload = doOtherStuff;

执行以上两条命令,最后onload会记住doOtherStuff函数而不是doStuff函数

而$(document).ready()可以一次执行两个函数

3.1.3 缩短代码的简写方式

$(document).ready()等价于$()

3.1.4 向.ready()回调函数中传入参数

当$引起冲突的时候,可以使用jQuery.noConflict()让出$,避免冲突

之后可以这样使用$:

jQuery(document).ready(function($)){}


3.2简单的事件

3.2.1 简单的样式转换器

初始效果:

html:

<!DOCTYPE html><html lang="en">  <head>    <meta charset="utf-8">    <title>A Christmas Carol</title>    <link rel="stylesheet" href="03.css" type="text/css" />    <script src="jquery.js"></script>    <script src="03.js"></script>  </head>  <body>    <div id="container">      <div id="switcher" class="switcher">        <h3>Style Switcher</h3>        <button id="switcher-default">          Default        </button>        <button id="switcher-narrow">          Narrow Column        </button>        <button id="switcher-large">          Large Print        </button>      </div>      <div id="header">        <h2>A Christmas Carol</h2>        <h2 class="subtitle">In Prose, Being a Ghost Story of Christmas</h2>        <div class="author">by Charles Dickens</div>      </div>      <div class="chapter" id="chapter-preface">        <h3 class="chapter-title">Preface</h3>        <p>I HAVE endeavoured in this Ghostly little book, to raise the Ghost of an Idea, which shall not put my readers out of humour with themselves, with each other, with the season, or with me.  May it haunt their houses pleasantly, and no one wish to lay it.</p>        <p>Their faithful Friend and Servant,</p>        <p>C. D.</p>        <p>December, 1843.</p>      </div>      <div class="chapter" id="chapter-1">        <h3 class="chapter-title">Stave I: Marley's Ghost</h3>        <p>MARLEY was dead: to begin with. There is no doubt whatever about that. The register of his burial was signed by the clergyman, the clerk, the undertaker, and the chief mourner. Scrooge signed it: and Scrooge's name was good upon 'Change, for anything he chose to put his hand to. Old Marley was as dead as a door-nail.</p>        <p>Mind! I don't mean to say that I know, of my own knowledge, what there is particularly dead about a door-nail. I might have been inclined, myself, to regard a coffin-nail as the deadest piece of ironmongery in the trade. But the wisdom of our ancestors is in the simile; and my unhallowed hands shall not disturb it, or the Country's done for. You will therefore permit me to repeat, emphatically, that Marley was as dead as a door-nail.</p>        <p>Scrooge knew he was dead? Of course he did. How could it be otherwise? Scrooge and he were partners for I don't know how many years. Scrooge was his sole executor, his sole administrator, his sole assign, his sole residuary legatee, his sole friend, and sole mourner. And even Scrooge was not so dreadfully cut up by the sad event, but that he was an excellent man of business on the very day of the funeral, and solemnised it with an undoubted bargain.</p>        <p>The mention of Marley's funeral brings me back to the point I started from. There is no doubt that Marley was dead. This must be distinctly understood, or nothing wonderful can come of the story I am going to relate. If we were not perfectly convinced that Hamlet's Father died before the play began, there would be nothing more remarkable in his taking a stroll at night, in an easterly wind, upon his own ramparts, than there would be in any other middle-aged gentleman rashly turning out after dark in a breezy spot—say Saint Paul's Churchyard for instance— literally to astonish his son's weak mind.</p>        <p>Scrooge never painted out Old Marley's name. There it stood, years afterwards, above the warehouse door: Scrooge and Marley. The firm was known as Scrooge and Marley. Sometimes people new to the business called Scrooge Scrooge, and sometimes Marley, but he answered to both names. It was all the same to him.</p>        <p>Oh! But he was a tight-fisted hand at the grind-stone, Scrooge! a squeezing, wrenching, grasping, scraping, clutching, covetous, old sinner! Hard and sharp as flint, from which no steel had ever struck out generous fire; secret, and self-contained, and solitary as an oyster. The cold within him froze his old features, nipped his pointed nose, shrivelled his cheek, stiffened his gait; made his eyes red, his thin lips blue; and spoke out shrewdly in his grating voice. A frosty rime was on his head, and on his eyebrows, and his wiry chin. He carried his own low temperature always about with him; he iced his office in the dog-days; and didn't thaw it one degree at Christmas.</p>        <p>External heat and cold had little influence on Scrooge. No warmth could warm, no wintry weather chill him. No wind that blew was bitterer than he, no falling snow was more intent upon its purpose, no pelting rain less open to entreaty. Foul weather didn't know where to have him. The heaviest rain, and snow, and hail, and sleet, could boast of the advantage over him in only one respect. They often "came down" handsomely, and Scrooge never did.</p>        <p>Nobody ever stopped him in the street to say, with gladsome looks, "My dear Scrooge, how are you? When will you come to see me?" No beggars implored him to bestow a trifle, no children asked him what it was o'clock, no man or woman ever once in all his life inquired the way to such and such a place, of Scrooge. Even the blind men's dogs appeared to know him; and when they saw him coming on, would tug their owners into doorways and up courts; and then would wag their tails as though they said, "No eye at all is better than an evil eye, dark master!"</p>        <p>But what did Scrooge care! It was the very thing he liked. To edge his way along the crowded paths of life, warning all human sympathy to keep its distance, was what the knowing ones call "nuts" to Scrooge.</p>        </div>    </div>  </body></html>

效果1:

单击Large Print按钮时,页面的文字变大

css:

body.large .chapter {  font-size: 1.5em;}

js:

$(document).ready(function() {  $('#switcher-large').bind('click', function() {    $('body').addClass('large');  });});

3.2.2 启用其他按钮

效果2:

启用其他按钮

css:

body.narrow .chapter {  width: 250px;}

js:

$(document).ready(function() {  $('#switcher-default').bind('click', function() {    $('body').removeClass('narrow');    $('body').removeClass('large');  });  $('#switcher-narrow').bind('click', function() {    $('body').addClass('narrow');    $('body').removeClass('large');  });  $('#switcher-large').bind('click', function() {    $('body').removeClass('narrow');    $('body').addClass('large');  });});

3.2.3 事件处理程序的环境

效果3:

点击按钮时,将被点击的按钮加粗

css:

.selected {  font-weight: bold;}

js:

$(document).ready(function() {  $('#switcher-default')  .addClass('selected')  .bind('click', function() {    $('body').removeClass('narrow');    $('body').removeClass('large');    $('#switcher button').removeClass('selected');    $(this).addClass('selected');  });  $('#switcher-narrow').bind('click', function() {    $('body').addClass('narrow');    $('body').removeClass('large');    $('#switcher button').removeClass('selected');    $(this).addClass('selected');  });  $('#switcher-large').bind('click', function() {    $('body').removeClass('narrow');    $('body').addClass('large');    $('#switcher button').removeClass('selected');    $(this).addClass('selected');  });});


3.2.4 进一步合并

js代码简化:

$(document).ready(function() {  $('#switcher-default').addClass('selected');  $('#switcher button').bind('click', function() {    var bodyClass = this.id.split('-')[1];    $('body').removeClass().addClass(bodyClass);    $('#switcher button').removeClass('selected');    $(this).addClass('selected');  });});

3.2.5 简写的事件

提供了以下的简写事件:

blur,focus

click,dbclick

load,unload

select,change

keydown,keypress,keyup

mousedown,mouseup,mousemove,mouseout,mouseover

error,resize,submit,scroll


3.3 复合的事件

3.3.1 显示和隐藏高级特性

效果4:

点击switcher div时,按钮显示或者隐藏

css:

.hidden {  display: none;}

js:

$(document).ready(function() {  $('#switcher h3').click(function() {    $('#switcher button').toggleClass('hidden');  });});

3.3.2 突出显示可单击的项

效果5:

进入switcher标题时,将鼠标显示为可单击的

css:

.hover {  cursor: pointer;  background-color: #afa;}

js:

$(document).ready(function() {  $('#switcher h3').hover(function() {    $(this).addClass('hover');  }, function() {    $(this).removeClass('hover');  });});

其中第一个函数是鼠标进入时执行,第二个函数是鼠标出去时执行


3.4 事件的旅程

事件捕获:在事件发生的时候,首先将事件交给最外层的元素,依次向内,直到具体元素。

事件冒泡:在事件发生的时候,首先将事件交给最内层的元素,依次向外,直到最后。

不同的浏览器采取以上两种中不同的策略,

jQuery为了浏览器的兼容性,总是先捕获冒泡事件,即总是具体元素得到事件。


3.5 通过事件对象改变事件的旅程

效果6:

jQuery采用冒泡策略可能的问题,点击button会使div隐藏

js:

$(document).ready(function() {//默认按钮加粗$('#switcher-default').addClass('selected');//01button点击事件$('#switcher button').bind('click',function(){//得到所点击按钮的样式var bodyClass = this.id.split('-')[1];//改变body样式$('body').removeClass().addClass(bodyClass);//改变默认按钮$('#switcher button').removeClass();$(this).addClass('selected');});//02隐藏和显示button$('#switcher').click(function() {$('#switcher button').toggleClass('hidden');});});

理想中应该是,点击switcher div会显示和隐藏button,

而点击button会改变body样式,

但是由于冒泡策略使得点击button改变body样式之后button也隐藏了。

3.5.1 事件目标

解决办法一:使用事件目标

js:

//02隐藏和显示button$('#switcher').click(function(event) {//错误的//$('#switcher button').toggleClass('hidden');//使用事件目标if(event.target == this){$('#switcher button').toggleClass('hidden');}});

3.5.2 停止事件传播

解决办法二:停止事件传播

这个方式不推荐跨浏览器使用

event.stopPropagation();

3.5.3 默认操作

a链接点击之后除了点击事件,还有自己的默认操作——打开网址,

停止事件传播可以停止事件的传播,但是并不能停止这种默认的传播,

可以使用.preventDefault()方法,

事件处理程序返回false时,是对以上两种方法的默认调用。

3.5.4 事件委托

事件冒泡也有可利用的时候,比如事件委托就是利用事件冒泡的,

当一个表格有很多行,每行又要注册点击事件,

而使用jQuery的隐式迭代,性能不好,

所以需要使用事件委托。

js:

$(document).ready(function() {  $('#switcher').hover(function() {    $(this).addClass('hover');  }, function() {    $(this).removeClass('hover');  });});$(document).ready(function() {  $('#switcher-default').addClass('selected');  $('#switcher').click(function(event) {    if ($(event.target).is('button')) {      var bodyClass = event.target.id.split('-')[1];      $('body').removeClass().addClass(bodyClass);      $('#switcher button').removeClass('selected');      $(event.target).addClass('selected');    } else {      $('#switcher button').toggleClass('hidden');    }  });});

3.5.4 事件委托的方法


3.6 移除事件处理程序

js:

$(document).ready(function() {  $('#switcher').click(function(event) {    if (!$(event.target).is('button')) {      $('#switcher button').toggleClass('hidden');    }  });  $('#switcher-narrow, #switcher-large').click(function() {    $('#switcher').unbind('click');  });});

3.6.1 事件的命名空间

js:

$(document).ready(function() {  $('#switcher').bind('click.collapse', function(event) {    if (!$(event.target).is('button')) {      $('#switcher button').toggleClass('hidden');    }  });  $('#switcher-narrow, #switcher-large').click(function() {    $('#switcher').unbind('click.collapse');  });});

3.6.2 重新绑定事件


3.7 模仿用户操作

点击:trigger('click')或者click()

键盘事件:

如果想知道用户按了哪个键,应该侦听keyup或keydown事件,

如果想知道用户输入的是什么字符,应该侦听keypress事件。

完整的一份代码:

js:

$(document).ready(function() {  // Enable hover effect on the style switcher  $('#switcher').hover(function() {    $(this).addClass('hover');  }, function() {    $(this).removeClass('hover');  });  // Allow the style switcher to expand and collapse.  var toggleSwitcher = function(event) {    if (!$(event.target).is('button')) {      $('#switcher button').toggleClass('hidden');    }  };  $('#switcher').bind('click', toggleSwitcher);  // Simulate a click so we start in a collaped state.  $('#switcher').click();  // The setBodyClass() function changes the page style.  // The style switcher state is also updated.  var setBodyClass = function(className) {    $('body').removeClass().addClass(className);    $('#switcher button').removeClass('selected');    $('#switcher-' + className).addClass('selected');    $('#switcher').unbind('click', toggleSwitcher);    if (className == 'default') {      $('#switcher').bind('click', toggleSwitcher);    }  };  // begin with the switcher-default button "selected"  $('#switcher-default').addClass('selected');  // Map key codes to their corresponding buttons to click  var triggers = {    D: 'default',    N: 'narrow',    L: 'large'  };  // Call setBodyClass() when a button is clicked.  $('#switcher').click(function(event) {    if ($(event.target).is('button')) {      var bodyClass = event.target.id.split('-')[1];      setBodyClass(bodyClass);    }  });  // Call setBodyClass() when a key is pressed.  $(document).keyup(function(event) {    var key = String.fromCharCode(event.keyCode);    if (key in triggers) {      setBodyClass(triggers[key]);    }  });});


3.8 小结


3.9 练习