网络编程
位置:首页>> 网络编程>> JavaScript>> javascript 变速加数功能实现代码

javascript 变速加数功能实现代码

  发布时间:2024-08-27 03:48:19 

标签:javascript,变速加数

用户单击其中一个按钮,可以让数字加1,单击另外一个按钮则让数字减1,如果按住按钮不放,文本框的数值会越加越快或越减越快,即变速加数功能。
比如你打开电脑的“时间和日期属性”窗口,你按下图红框标识的上下按钮调整时间,试着单击与按着鼠标不放,你会发现它的功能与我说的一样(准确说还是有区别的,它按下鼠标不放加数速度是快了,但不会越来越快。我的例子是越加越快,这更适合数值比较大的数据提供场合)。

代码很简单,都加了注释,就不知道实现的够不够科学,如果你有更好的建议不妨与我分享。HTML与JavaScript代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>变速加数功能实现</title> </head> <body> <input name="textBox" type="text" id="textBox" value="1" /> <input name="add" type="button" onmousedown="addNum.mouseDownHandle()" onmouseup="addNum.mouseUpHandle()" id="add" value="增加" />按住按钮不放,数值将会越加越快 <script type="text/javascript"> /** * 加数类 * @param {String} textBoxId 文本框ID */ function clsAddNum(textBoxId) { var step = 1; //默认步长 var changeStepTimer = null; //改变速度计数器 var setValueTimer = null; //设置值计数器 /** * 改变速度私有方法 */ var changeStep = function() { //每隔1秒速度加5 changeStepTimer = setInterval(function(){step += 5}, 1000); } /** * 设置值私有方法 */ var setValue = function() { var textValue = parseInt(document.getElementById(textBoxId).value); document.getElementById(textBoxId).value = textValue + step; setValueTimer = setTimeout(setValue,200); //每隔200毫秒更新文本框数值一次 } /** * 按下鼠标处理函数 */ this.mouseDownHandle = function() { changeStep(); setValue(); } /** * 松开鼠标处理函数 */ this.mouseUpHandle = function() { //停止变速和改变文本框的值 clearInterval(changeStepTimer); clearTimeout(setValueTimer); step = 1; //恢复默认速度 } } //实例化类 var addNum = new clsAddNum('textBox'); </script> </body> </html>



作者:WebFlash
出处:http://webflash.cnblogs.com

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com