簡體   English   中英

如何實現按住按鈕 javascript?

[英]How do I implement press and hold button javascript?

我是一個完全的新手,正在尋找有關實現 javascript 的說明。 我正在嘗試用按鈕和文本字段替換 YUI slider。 我正在嘗試實現按鈕,當按住時,將繼續使文本字段增加,最好以越來越快的速度增加。 http://www.blackbird502.com/white.htm)我在頭部的 java 標簽中有這個:

function holdit(btn, action, start, speedup) {
var t;

var repeat = function () {
    action();
    t = setTimeout(repeat, start);
    start = start / speedup;
}

btn.mousedown = function() {
    repeat();
}

btn.mouseup = function () {
    clearTimeout(t);
}

/* to use */
holdit(btn, function () { }, 1000, 2); 
/* x..1000ms..x..500ms..x..250ms..x */

我不知道如何在正文中實現按下並按住以下內容:

<form><input type=button value="UP"  class="btn" onClick="javascript:this.form.amount.value++;"><br /><input type=text name=amount value=5 class="text"><br /> <input type=button value="DOWN"  class="btn" onClick="javascript:this.form.amount.value--;" ></form>

可能嗎? 謝謝。

這段代碼應該做你正在尋找的一切; 它非常松散地基於 tj111 的示例。 我試圖使其盡可能可重復使用,並且不需要將 JavaScript 與 HTML 混合。

您確實需要向按鈕( btnUPbtnDOWN )和文本字段( amount )添加 ID。 您可以在window.onload語句中更改這些 ID。

// This function creates a closure and puts a mousedown handler on the element specified in the "button" parameter.
function makeButtonIncrement(button, action, target, initialDelay, multiplier){
    var holdTimer, changeValue, timerIsRunning = false, delay = initialDelay;
    changeValue = function(){
        if(action == "add" && target.value < 1000)
            target.value++;
        else if(action == "subtract" && target.value > 0)
            target.value--;
        holdTimer = setTimeout(changeValue, delay);
        if(delay > 20) delay = delay * multiplier;
        if(!timerIsRunning){
            // When the function is first called, it puts an onmouseup handler on the whole document 
            // that stops the process when the mouse is released. This is important if the user moves
            // the cursor off of the button.
            document.onmouseup = function(){
                clearTimeout(holdTimer);
                document.onmouseup = null;
                timerIsRunning = false;
                delay = initialDelay;
            }
            timerIsRunning = true;
        }
    }
    button.onmousedown = changeValue;
}

//should only be called after the window/DOM has been loaded
window.onload = function() {
    makeButtonIncrement(document.getElementById('btnUP'), "add", document.getElementById('amount'), 500, 0.7);
    makeButtonIncrement(document.getElementById('btnDOWN'), "subtract", document.getElementById('amount'), 500, 0.7);
}

這有點快速和骯臟,但它應該給你一個開始。 基本上,您想設置一些可以使用的初始“常量”來獲得所需的行為。 增量之間的初始時間為 1000 毫秒,並且在每次迭代中,如果變為該值的 90%(1000、990、891、... 100)並在 100 毫秒處停止變小。 您可以調整此因素以獲得更快或更慢的加速。 我相信 rest 與我認為您想要的非常接近。 看來您只是錯過了活動分配。 window.onload ,您會看到我將onmouseuponmousedown事件分配給僅使用初始超時調用increment()decrement()函數的函數,或者使用ClearTimeout() function 來停止計數器。

編輯:我稍微改變了這個以修復錯誤。 現在,如果您將鼠標指針從按鈕上移開並釋放,它將停止計數器。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
    <title><!-- Insert your title here --></title>
    <script>

      // Fake Constants
      var INITIAL_TIME = 1000;
      var ACCELERATION = .9;
      var MIN_TIME = 100;

      // create global variables to hold DOM objects, and timer
      var up = null,
        down = null,
        count = null,
        timer = null;

      // Increment the counter
      function increment (time) {
        // decrease timeout by our acceleration factor, unless it's at the minimum
        time = (time * ACCELERATION > MIN_TIME) ? (time * ACCELERATION) : MIN_TIME;
        count.value ++ ;
        // set the timeout for the next round, and pass in the new smaller timeout
        timer = setTimeout(
                  function () {
                    increment(time);
                  }, time);
      }
      // Same as increment only subtracts one instead of adding.
      // -- could easily make one function and pass an pos/neg factor instead
      function decrement (time) {
        time = time * ACCELERATION > MIN_TIME ? (time * ACCELERATION) : MIN_TIME;
        count.value --;
        timer = setTimeout(
                  function () {
                    decrement(time);
                  }, time);
     }

     // Initialize the page after all the forms load
     window.onload = function () {
       // initialization function

       // assign DOM objects to our vars for ease of use.
       up = document.getElementById('up_btn');
       down = document.getElementById('dwn_btn');
       count = document.getElementById('count');

       // create event handlers for mouse up and down
       up.onmousedown = function () {
         increment(INITIAL_TIME);
       }
        down.onmousedown = function () {
         decrement(INITIAL_TIME);
       }

       document.onmouseup = function () {
         clearTimeout(timer);
       }

     }

  </script>
</head>
<body>
  <!-- Insert your content here -->

  <form name="the_form">
    <input type="button" value="Up" id="up_btn" /><br />
    <input type="button" value="Down" id="dwn_btn" /></br>

    <br />
    Count: 
    <input type="text" value="0" id="count" />

  </form> 

</body>
</html>

最簡單的方法是為每個按鈕添加一個 ID,然后使用它們來檢索元素並添加事件。

//should only be called after the window/DOM has been loaded
window.onload = function() {
  //the buttons
  var btnUP = document.getElementById('btnUP');
  var btnDOWN = document.getElementById('btnDOWN');

  //the amount
  var amount = document.getElementById('amount');

  //actions to occur onclick
  var upClick = function() {
    amount.value++;
  }
  var downClick = function() {
    amount.value--;
  }

  //assign the actions here
  holdit(btnUP, upClick, 1000, 2);
  holdit(btnDOWN, downClick, 1000, 2); 

}


<form>
  <input type=button value="UP"  class="btn" id='btnUP'>
  <br />
  <input type=text name=amount value=5 class="text" id='amount'>
  <br /> 
  <input type=button value="DOWN"  class="btn" id='btnDOWN'>
</form>

一個不容忽視的方面是您正在連接到 onclick 事件 - 這發生在完全單擊(鼠標鍵向下和向上鍵)。 聽起來您想聽另一個不同的事件,http://www.w3schools.com/jsref/jsref_onmousedown.asp'>onMouseDown。 我認為,如果您要實施其他一些基於計時器的解決方案,那么您已經獲得了您所要求的功能。

祝你好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM