2009-03-31 64 views
6

Soy un novato completo, buscando instrucciones para implementar javascript. Estoy intentando reemplazar un control deslizante YUI con botones y un campo de texto. Intento conseguir botones que, cuando se mantienen pulsados, continúen haciendo que el campo de texto aumente, preferiblemente a un ritmo más rápido y más rápido. (http://www.blackbird502.com/white.htm)I tener esto en la etiqueta de java en la cabeza:¿Cómo implemento presionar y mantener presionado el botón javascript?

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 */ 

no tengo idea de cómo implementar la prensa y mantenga a la siguiente en el cuerpo:

<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> 

¿Es posible Gracias?.

Respuesta

5

Este código debe hacer todo lo que está buscando; se basa muy poco en el ejemplo de tj111. Traté de hacerlo lo más reutilizable posible, y no necesita JavaScript mezclado con el HTML.

Necesita agregar ID a los botones (btnUP y btnDOWN) y al campo de texto (amount). Puede cambiar estos ID en la declaración window.onload.

// 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); 
} 
+0

Esto funciona perfectamente: http://www.blackbird502.com/white2.htm ¡GRACIAS! – couchua

+0

¿Hay alguna posibilidad de que exista un límite mínimo/máximo para la "cantidad", como 0-1000 o más? – couchua

+0

Actualicé la respuesta para agregar límites. Traté de hacer que este código fuera bastante legible, así que, por supuesto, jugar con él, romperlo y mejorarlo. Esa es la mejor manera de aprender cualquier idioma. – s4y

0

El método más fácil sería simplemente añadir un ID a cada uno de los botones, a continuación, utilizar aquellos para recuperar los elementos y añadir los eventos.

//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> 
2

Esto es un poco rápido y sucio, pero debería darle un comienzo. Básicamente, desea configurar algunas "constantes" iniciales con las que pueda jugar para obtener el comportamiento deseado. El tiempo inicial entre incrementos es 1000 ms, y en cada iteración si se convierte en 90% de eso (1000, 990, 891, ... 100) y deja de reducirse a 100 ms. Puede modificar este factor para obtener una aceleración más rápida o más lenta. El resto creo que está muy cerca de lo que creo que estabas buscando. Parece que solo estabas perdiendo las asignaciones de eventos. En el window.onload verá que asigno los eventos onmouseup y onmousedown a funciones que solo llaman a las funciones increment() o decrement() con su tiempo de espera inicial, o la función ClearTimeout() para detener el contador.

EDITAR: Cambié esto ligeramente para corregir el error. Ahora, si mueve el puntero del mouse fuera del botón y lo suelta, se detendrá el contador.

<!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> 
+1

Ooops, mi código establece el evento onmouseup para el botón, así que tiene el error al que se refiere SydneySM en su solución. –

+0

Acabo de trabajar esto en la página, y funciona perfectamente: http://www.blackbird502.com/white1.htm Voy a probar SidneySM a continuación para tratar de evitar el "error", aunque no hay evidencia de un "error" desde el punto de vista de un novato. ¡GRACIAS! – couchua

+0

Cambié el código para corregir el error. Acabo de adjuntar el evento onmouseup al documento. El crédito va a SidneySM por atrapar eso. –

0

Un aspecto que no debe olvidarse es que se está enganchando en el evento onclick - lo que sucede en un clic completa (llave del ratón y la tecla hacia arriba). Parece que desea escuchar otro evento distinto, http://www.w3schools.com/jsref/jsref_onmousedown.asp'>onMouseDown. Creo que si implementara algunas de las otras soluciones basadas en temporizadores, ya le daría la funcionalidad que está solicitando.

¡Buena suerte!

Cuestiones relacionadas