事件绑定
- jQuery事件绑定
- 一些经典案例
一、jQuery的事件绑定
1.1、标准绑定方式
语法:jQuery对象.事件方法(回掉函数);
<body>
<input type="text" id="test1">
</body>
<script>
$(function () {
$("#test1").change(function () {//修改内容事件
alert("输出框的内容被修改了...");
});
/*jQuery的链式编程*/
$("#test1").mouseover(function () {//光标移入事件
alert("光标移入......");
}).mouseout(function () {//光标移出事件
alert("光标移出......");
});
});
</script>
1.2、添加、移除绑定事件
- 语法(添加):
jQuery对象.on(事件名称,回掉函数);
- 语法(移除):
jQuery对象.off(事件名称,回掉函数);
<body>
<div id="testDiv">DIV...</div>
<button id="test1">给DIV绑定单击事件</button>
<button id="test2">移除DIV的单击事件</button>
</body>
<script>
$("#test1").click(function () {
//给DIV绑定单击事件
$("#testDiv").on("click",function () {
alert("DIV被点击了...")
})
});
$("#test2").click(function () {
//给DIV解除绑定事件,如果指定具体的事件名称,则解除所有事件
$("#testDiv").off("click");
});
</script>
1.3、更改单击事件的回掉函数
语法:jQuery对象.toggle(回掉函数1,回掉函数2......)
<body>
<div id="testDiv">单击变猛男色<br/>再次单击变绿色</div>
</body>
<script>
$("#testDiv").toggle(function () {//只能作用click事件
$(this).css("backgroundColor","hotpink");
},function () {
$(this).css("backgroundColor","yellowgreen");
});//可以同时注册多个回掉函数
</script>
二、一些经典案例
2.1、广告的显示和隐藏
需求:1、当页面加载完成3秒后,自动显示广告(图片)
2、广告(图片)显示5秒后,自动消失
<body>
<div id="testDiv" style="display: none">
<img src="../img/ztfn.jpg" alt="图片失效">
</div>
<p>这是一个段落...</p>
</body>
<script>
$(function () {
window.setTimeout(showImg,3000);//3秒后显示图片
window.setTimeout(hiddenImg,8000);//显示5秒后隐藏图片
});
function showImg() {
$("#testDiv").slideDown();//显示div,方式为滑动,效果默认
}
function hiddenImg() {
$("#testDiv").slideUp();//隐藏DIV,方式为滑动,效果默认
}
</script>
2.1、抽奖
需求:1、点击开始按钮,开始轮播小图片
2、点击停止按钮,停止轮播图片,并将大图片展示于下边
<body>
<div id="left">
<img src="../img/test1.jpg" alt="图片失效" align="top" width="100px" id="smallImg">
<button id="start">开始</button>
<button id="stop" disabled="disabled">停止</button>
</div>
<hr/>
<div id="right">
<img src="../img/test1.jpg" alt="图片失效" width="400px" id="bigImg" style="display: none">
</div>
</body>
<!--JS代码-->
<script>
var imgs = ["../img/test1.jpg","../img/test2.jpg","../img/test3.jpg","../img/test4.jpg","../img/test5.jpg","../img/test6.jpg","../img/test7.jpg"];
$(function () {
var startId;
$("#start").click(function () {//开始按钮的单击事件
$("#start").attr("disabled",true);//将开始按钮设置为不可点击
$("#stop").attr("disabled",false);//将停止按钮设置为可点击
startId = setInterval(function () {
var random = Math.floor(Math.random()*7);//(0-0.999)*7=0-6.999,取整0-6
$("#smallImg").prop("src",imgs[random]);
},100);
});
$("#stop").click(function () {//停止按钮的单击事件
$("#start").attr("disabled",false);//将开始按钮设置为可点击
$("#stop").attr("disabled",true);//将停止按钮设置为不可点击
clearInterval(startId);
$("#bigImg").prop("src",$("#smallImg").prop("src"));
$("#bigImg").fadeIn(800,"linear");
});
});
</script>
*{
margin:0;
padding:0;
}
#left{
height: 150px;
margin:10px 0 10px 20px;
}
#right{
width: 400px;
height:560px;
margin:10px 0 10px 20px;
border:hotpink 2px solid;
}
#start,#stop{
width: 150px;
height: 100px;
margin-left: 20px;
}