码迷,mamicode.com
首页 > Web开发 > 详细

使用jQuery让事件动起来

时间:2016-04-26 20:00:38      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:

目录:

  • 三步实现jQuery方式处理事件
  • $(document).ready()与window.onload
  • this和$(this)
  • 常用的hover()和toggle()
  • 通过点击文章标题展开、隐藏新闻内容

三步实现jQuery方式处理事件

发生在Web页面的每一件事情都可以称为事件,为了使Web页面具有交互性,我们采用的方法是通过编写程序来响应事件。

例如,鼠标移动到导航栏时显示帅气的下拉菜单;鼠标点击标题时展开段落内容;用键盘来控制JavaScript动画等。我们在文末会给一个简单又酷炫的示例。

jQuery极大增强并扩展了基本事件的处理机制,同时也让我们从恼人的兼容性问题中大大地解放。更好的消息是,jQuery进行事件处理更加简单易用,废话不多说,我们下面看如何用三步进行jQuery的事件处理。

选择元素

用户在Web页面中通常是和页面的元素进行交互的,比如点击某个按钮,移动到某个div,点击链接等等。当分配事件的时候,我们第一步要做的就是选择该元素。

jQuery支持使用css选择器来选择我们想要操作的页面部分,例如:

$(‘#id-name‘)      //通过id选择器
$(‘.class-name‘)   //通过类选择器
$(‘a‘)             //通过元素选择器

为元素分配事件

在选择一个元素之后,接下来就是为该元素分配指定的事件,事件的种类很多。例如当我们的鼠标移动到某个<a>链接上时:

$(‘a‘).mouseover()

当我们点击id为button1的按钮时:

$(‘#button1‘).click()

为事件传递函数

第二步只是指定了元素的某个事件,但是当该事件触发时具体做什么我们还没有指定。这一步就是为事件指定处理函数,即当事件触发时,执行该函数的操作。

比如,当我们鼠标移动到导航栏时,显示隐藏的id为submenu的子菜单:

$(‘#mainmenu‘).mouseover(function(){
    $(‘#submenu‘).show();
  }
);

上面是使用传入匿名函数作为参数的方法,当然我们也可以传递之前定义好的函数名,以上代码可以重写如下:

function showSubmenu(){
  $(‘#submenu‘).show();
}
$(‘#mainmenu‘).mouseover(showSubmenu);

这里需要注意,在将函数名指定为事件处理参数时,是没有圆括号的。不知大家还记不记得,如果我们传入带圆括号的函数,那么该函数会立即执行,传入的参数实际上是该函数执行的结果。而没有圆括号,传入的是函数的引用。

$(document).ready()与window.onload

当文档完全下载到浏览器时,会触发window.onload事件,此时,页面上全部元素对于JavaScript而言都是可操作的。(document).ready()(document).ready()会在页面DOM准备就绪的时候就可以使用了。当页面需要加载较多的资源的时候这种差异便会体现出来。

比如我们在加载相册类的界面的时候,使用window.onload要等到每一幅图片都加载完毕才会触发该事件,这通常需要数秒的时间。如果在这之前用户进行了某种页面的操作,这些结果都是不可预料的。但是使用$(document).ready()会在DOM树解析完成时即可,也就是说页面会“更早地准备好”。

通常情况下$(document).ready()是一个更好的方法,作为jQuery初学者只需要知道每次把需要执行的代码放在以下片段即可:

$(document).ready(function() {

}); // end ready

由于$(document).ready()十分常用,可以简写为以下形式:

$(function(){

});

但是(document).ready()(document).ready()是在document的jQuery对象上调用.ready()方法的代码过程。初学者没太大必要做这样的简化。

this和$(this)

this几乎是在所有语言中都随处可见的一个关键字,它的含义也万变不离其宗。在jQuery中,this引用正在调用匿名函数的元素。比如说:

$(‘#button1‘).click(function(){
  $(this).val("OK!");
});

上面的代码中的this就是对id为button1的按钮元素的引用。

$(this)则是this引用元素对应的jQuery对象,在jQuery中,对元素的操作是通过对应的jQuery对象实现的。this的使用十分常见,后面我们会举例说明。

常用的hover()和toggle()

hover()

在鼠标事件中,mouseover和mouseout事件通常组合使用。例如,当光标移动到某menu上,出现一个下拉菜单,移出时隐藏该下拉菜单。这样的组合十分常见,jQuery提供了一种简单的方式——hover()。

hover()接收2个函数作为参数,第一个函数表示当鼠标移动到该位置时执行的操作,第二个函数表示鼠标离开时所要执行的操作。我们以上面的menu操作为例,当鼠标移动到menu按钮时,弹出下拉菜单,移出时,隐藏下来菜单:

$(‘#menu‘).hover(
  function(){
    $(‘#submenu‘).show();
  },
  function(){
    $(‘#submenu‘).hide();
  }
);

该事件可以用以下图示表示:

技术分享

toggle()

toggle()与hover()的用法十分相似,它接收若干个函数作为参数。第一次点击时执行第一个函数,第二次点击时执行第二个函数……,当执行到最后一个函数的时候,循环回第一个函数。

我们常用的是传入2个函数作为参数,比如第一次点击某个标题,显示段落内容,再次点击隐藏段落内容:

$(‘.h2‘).hover(
  function(){
    $(this).next(.content).show();
  },
  function(){
    $(this).next(.content).hide();
  }
);

通过点击文章标题展开、隐藏新闻内容

很多时候,我们希望在某个页面中只显示文章的标题,这样我们就能快速找到自己感兴趣的部分。当找到我们的目标文章的时候,在本地展开而不是请求链接到另一个页面会明显地提升用户体验,这里,我们就用以上介绍的方法实现这样一个有趣的功能。

1、将以下代码复制的文本编辑工具,不妨保存为test1.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>A Simple eg.</title>
<script src="jquery-1.7.2.min.js"></script>
<style type="text/css">
html, body{
    background-color: #666;
}
h1 {
    font-size: 32px;
    color: white;
    text-shadow: 1px 1px 1px rgba(0,0,0,.75);
    border-bottom: solid 1px rgba(255,255,255,.5);
    margin-bottom: 0.75em;
}
h2 {
    background: url(open.png) no-repeat 0 11px;
    padding: 10px 0 0 25px;
    cursor: pointer;
}
h2.close {
    background-image: url(close.png);
}
p {
    font-size: 18px;
    color: white;
    font-family: ‘ColaborateLightRegular‘, Arial, sans-serif;
    line-height: 125%;
    margin-bottom: 10px;
}
</style>
<script>
$(document).ready(function() {

}); // end ready
</script>
</head>
<body>
<body>
<div class="header">
    <p class="logo">Easy <i>&</i> News</p>
</div>
<div class="content">
<h1>Lately News</h1>
<h2>Warriors without Curry still beat Rockets in Game 2</h2>
      <div class="details">
        <p>As Stephen Curry emphatically waved his arms to ignite the crowd and coached from the bench when he could do little else, Klay Thompson and the Golden State Warriors’ supporting cast picked up the slack for their absent NBA MVP to hold off the Houston Rockets115-106 on Monday night and take a 2-0 lead in their playoff series. Thompson scored 34 points and dished out five assists for the defending champions, playing without Curry because of an injured right ankle. Curry cut short his pregame warmup routine after appearing to be in discomfort as he was shooting while putting little pressure on the tender ankle.</p>
      </div>
<h2>Liverpool boss Jurgen Klopp: Win over Borussia Dortmund like Istanbul 2005 final</h2>
      <div class="details">
        <p>The Reds, who needed to score three goals in the last 33 minutes, won 4-3 at Anfield and 5-4 on aggregate thanks to Dejan Lovren’s stoppage-time header."I reminded the players about Liverpool being 3-0 down in the Champions League final to AC Milan," he said. "I know this is a place for big football moments. It was special."Liverpool won their fifth European Cup in Istanbul in 2005 after trailing Milan by three goals at half-time.Dortmund scored through Henrikh Mkhitaryan and Pierre-Emerick Aubameyang inside the first nine minutes and, after Divock Origi pulled one back for Liverpool, Marco Reus put the German side 4-2 up on aggregate.</p>
      </div>
<h2>Kobe Bryant: Don’t want Jazz to take it easy at all in my final game</h2>
      <div class="details">
        <p>The next time Lakers icon Kobe Bryant appears on the Staples Center court, it will be for the final game of his NBA career.Has Bryant looked forward to that final game, April 13 against the Utah Jazz, and imagined what it will be like?"I try not to do it too much," Bryant said Wednesday night, "and just make yourself emotional."</p>
      </div>
</div>
</body>
</body>
</html>

不要在意这段代码有多长,其中大段的只不过是新闻内容而已,接下来我们要做的准备工作是把代码中需要包含的open.png+close.png+jquery-1.7.2.min.js下载到和test.1.html相同目录中。

好了,双击test1.html在浏览器中预览效果如下:

技术分享

接下来就是我们大显身手的时候了,首先在以上代码的36行添加以下代码:

$(‘.details‘).hide();

这样我们的新闻内容就会隐藏起来:

技术分享

然后给新闻标题添加我们上面介绍的toggle()事件。第一次点击新闻标题,让内容显示,再次点击,内容隐藏,在$(‘.details‘).hide();后面添加以下代码:

$(‘.content h2‘).toggle(
  function(){
    $(this).next(‘.details‘).fadeIn();
  },
  function(){
    $(this).next(‘.details‘).fadeOut();
  }
);

保存再次加载test1.html,会发现当我们点击文章标题的时候,会淡入新闻内容,再次点击新闻内容淡出。是不是一个简单有不失帅气的效果?

接下来,为了更加美观,还记得我们上面下载的open.png和close.png吗?我们希望当新闻展开时,+号变为-号,隐藏时又变回+号。十分简单,代码中已经准备好了这样的效果:

h2.close {
    background-image: url(close.png);
}

我们只需要在新闻展开的时候,给标题添加一个close的class即可。在新闻关闭时删除该class:

$(‘.content h2‘).toggle(
  function(){
    $(this).next(‘.details‘).fadeIn();
    $(this).addClass(‘close‘);
  },
  function(){
    $(this).next(‘.details‘).fadeOut();
    $(this).removeClass(‘close‘);
  }
);

技术分享

点击标题,文章展开,+号变为-,再次点击,新闻隐藏,-号变回+,大功告成。

我们可以看到使用jQuery进行事件响应不论从效率、效果来看,都有明显的提高。当然这只是学习的初步体验,深入学习会让我们的代码更有质量。

使用jQuery让事件动起来

标签:

原文地址:http://blog.csdn.net/a153375250/article/details/51251721

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!