学学jQuery,实现个小功能练练手
需要用到定时器
html代码如下
<html> <head> <title></title> <script type="text/javascript" src="jquery-1.9.1.min.js"></script> </head> <body> <h2>ShowOrHide</h2> <META http-equiv="content-type" content="text/html;charset=utf8"> <input type="button" name="stop" value="咒立停"/> <input type="button" name="begin" value="颤抖吧"/> <div id="song" style="text-align: center; font-size: 100px;width:300px;"> <img id="gala" alt="我爱罗" src="gala.jpg" style="width:300px;height:300px"/> </div> <script type="text/javascript"> $(function () { $("h2").click(function () { //隐藏或显示标签 $("img#gala").slideToggle(); }); $("[name=‘stop‘]").click(function(){ window.clearInterval(timerlr); }); $("[name=‘begin‘]").click(function(){ window.clearInterval(timerlr);//非第一次使用定时器必须先停止,否则会导致时间混乱 timerlr = self.setInterval("move()", global.timespan); }); }); //声明全局变量对象,尽量减少污染 var global = { timespan: 10,//定时器间隔 vdirect: "down",//垂直滚动方向 hdirect: "right",//水平滚动方向 widthspan: 10,//单次宽度变化 heightspan: 10//单次高度变化 } var timerlr = self.setInterval("move()", global.timespan); function moveright() { $song = $("div#song"); var offset = $song.offset(); var left = offset.left + global.widthspan; $song.offset({ left: left, top: offset.top }); } function movedown() { $song = $("div#song"); var offset = $song.offset(); var top = offset.top + global.heightspan; $song.offset({ left: offset.left, top: top }); } function moveleft() { $song = $("div#song"); var offset = $song.offset(); var left = offset.left - global.widthspan; $song.offset({ left: left, top: offset.top }); } function moveup() { $song = $("div#song"); var offset = $song.offset(); var top = offset.top - global.heightspan; $song.offset({ left: offset.left, top: top }); } //进行水平和垂直方向的移动 function move() { $height=$(window).height(); $song = $("div#song"); //离底部还有10像素的距离时开始回弹 if ($song.offset().top + $song.height() >= $height-10) { global.vdirect = "up"; } else if ($song.offset().top <= 10) { global.vdirect = "down"; } if (global.vdirect == "down") { movedown(); } else if (global.vdirect == "up") { moveup(); } if ($song.offset().left + $song.width() >= $(window).width()-10) { global.hdirect = "left"; } //离右边界还有10像素距离还是回弹 else if ($song.offset().left <= 10) { global.hdirect = "right"; } if (global.hdirect == "right") { moveright(); } else if (global.hdirect == "left") { moveleft(); } } </script> </body> </html>
哥们用的图片,话说火影写的越来越没意思了