2009-03-31 6 views
6

나는 완전한 초보자이며, 자바 스크립트 구현에 대한 지침을 찾고있다. 유이 슬라이더를 버튼과 텍스트 필드로 대체하려고합니다. 아래 버튼을 계속 누르고 있으면 텍스트 필드가 더 빨라지고 빠른 속도로 계속 증가하는 버튼을 얻으려고합니다. (http://www.blackbird502.com/white.htm)I는 머리에 자바 태그이 있습니다어떻게 자바 스크립트를 구현하고 유지합니까?

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

이 가능 감사합니다 :

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

내가 언론을 구현하고 본문에 다음으로 유지하는 방법을 단서가 없다.

답변

5

이 코드는 원하는 모든 것을 처리해야합니다. 그것은 tj111의 예제에 매우 근거가 있습니다. 가능한 한 재사용 가능하도록 만들려고했는데 HTML과 JavaScript가 섞일 필요가 없습니다.

버튼 (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); 
} 
+0

완벽하게 작동합니다. http://www.blackbird502.com/white2.htm 고맙습니다! – couchua

+0

0-1000 정도의 "금액"에 최소/최대 한도를 설정하는 방법이있을 수 있습니다. – couchua

+0

한계를 추가하는 답이 업데이트되었습니다. 나는이 코드를 공정하게 읽을 수있게 만들려고 노력 했으므로 꼭 모든 것을 가지고 놀고, 깨뜨리고, 향상시켜야한다. 그것은 모든 언어를 배우는 가장 좋은 방법입니다. – s4y

0

가장 쉬운 방법은 다음, 각각의 버튼에 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> 
2

이것은 일종의 빠르고 더러운 일이지만 시작해야합니다. 기본적으로 원하는 초기 동작을 얻기 위해 사용할 수있는 몇 가지 초기 상수를 설정하려고합니다. 증가 사이의 초기 시간은 1000ms이고 각 반복마다 그 (1000, 990, 891, ... 100)의 90 %가되고 100ms에서 더 작아지는 것을 멈 춥니 다. 가속도를 높이거나 낮추려면이 요인을 조정할 수 있습니다. 내가 믿는 나머지는 내가 생각하는 것에 거의 가깝다. 방금 이벤트 할당이 누락 된 것 같습니다. window.onload에서 onmouseuponmousedown 이벤트를 초기 시간 제한을 사용하여 increment() 또는 decrement() 함수를 호출하는 함수에 할당하거나 카운터를 중지하는 함수 ClearTimeout()을 할당하는 것을 볼 수 있습니다.

편집 : 버그를 수정하기 위해 약간 변경했습니다. 이제 마우스 포인터를 버튼 밖으로 이동하여 놓으면 카운터가 중지됩니다. 간과하지

<!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, 내 코드는 onmouseup 이벤트를 버튼에 설정하므로 SydneySM이 그의 해결책에서 언급 한 버그가 있습니다. –

+0

방금 ​​페이지에서이 작업을했으며 완벽하게 작동합니다. http://www.blackbird502.com/white1.htm 초심자의 입장에서 '버그'에 대한 증거는 없지만 SidneySM은 아래에서 '버그'를 피하려고 시도합니다. 감사! – couchua

+0

버그를 수정하기 위해 코드를 변경했습니다. 방금 onmouseup 이벤트를 문서에 첨부했습니다. 그것을 잡기 위해 SidneySM에게 신용을 보냅니다. –

0

한 측면은 onclick 이벤트에 접선하고 있다는 것입니다 - 완벽한 클릭 (마우스 아래로 키와 키까지)에서 발생한다. 다른 별개의 이벤트 인 http://www.w3schools.com/jsref/jsref_onmousedown.asp'>onMouseDown을 듣고 싶어하는 것 같습니다. 만약 당신이 다른 타이머 기반 솔루션을 구현한다면, 이미 요구되는 기능을 얻을 수 있다고 생각합니다.

행운을 빈다.

관련 문제