javascript 變速加數功能實現代碼_javascript技巧

來源:互聯網
上載者:User
使用者單擊其中一個按鈕,可以讓數字加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>
[Ctrl+A 全選 注:如需引入外部Js需重新整理才能執行]

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.