本文实例讲述了JQuery中的事件及动画用法。分享给大家供大家参考。具体分析如下:
1.bind事件
代码如下:<script src="script/jquery-1.7.1.min.js"></script>
<script>
$(function () {
$("#divid h5.head").bind("click", function () { //bind事件,其中包含三个参数,第一个为事件,第二个为事件
alert($(this).text());
});
$("#divid h5.content").css("display", "none"); //css方法就是可以动态设置标签样式
});
$(function () {
$("#btnid").bind("click", function () {
if (bool == true) {
$("#btnid .content").css("display", "none");
bool = false;
$(this).val("显示");
}
else {
$("#btnid .content").css("display", "");
bool = true;
$(this).val("隐藏");
}
});
});
$(function () {
$("input[type=button]").bind("click", function () { //内容的显示与隐藏
var content = $("#divid .content");
if (content.is(":visible")) {
content.hide();
$(this).val("显示");
}
else {
content.show();
$(this).val("隐藏");
}
});
});
</script>
<body>
<div id="divid">
<h5 class="head">Rocky?</h5>
<div class="content">就让雨下下来 不用带伞 让一切完蛋 看被淋湿的心 多久才会晒干</div>
</div>
<input type="button" name="name" value="显示 " id="btnid" />
</body>
在上面的操作中我们新学习了bind事件,而bind事件是三个参数,第一个参数是事件的名字,例如:click,dbclick,mouseover等,第二个参数是data,即传递过来的事件对象,第三个参数是一个方法,即用来处理处 理绑定的事件函数这就是我们的一个特殊的事件;另外在这里还举例写了一个动画中的例子,即文本信息的显示或者隐藏,在还没有学习show()和 hide()之前我们一般是按照上面第一种方式来写的,定义一个bool类型的变量即可,这样写起来还是很简单的,但是在写显示隐藏时间处理按钮上面还是 蛮蛮烦的,所以在学习了show()和hide()后就简单许多了,就是直接可以隐藏和显示。可以对比一下,显然在代码的处理上简单啦。
2.toggle事件和事件冒泡
代码如下:<script>
$(function () {
$("input[type=button]").toggle(function () { //toggle两个参数都为事件,轮番调用
$(this).css("backgroundColor","red");
}, function () {
$(this).css("backgroundColor", "yellow");
});
});
$(function () {
$("div").each(function () {
$(this).bind("mouseup", function (e) {
alert(e.pageX); //输出鼠标的x方向的位置
alert(e.pageY); //输出鼠标的y方向的位置
alert(e.which); //输出鼠标的按键的选择,1为鼠标左键,2为滚轴按键,3为鼠标右键
新闻热点
疑难解答
图片精选