2015-04-16 38 views
0

我目前試圖讓我的網頁上爲移動和標籤更加用戶友好的,而且我有這個問題:我不能清除我的間隔與onmousedown事件設定onmouseup

我想一個按鈕來增加文本框的值,而按鈕被按下(onmousedown)。所以,我建立了我的按鈕,像這樣:

<span 
    class="glyphicon glyphicon-resize-full textIconBoxControll" 
    aria-hidden="true" 
    onmousedown="inter=setInterval(increaseFont, 300);" 
    onmouseup="clearInterval(inter);" 
    onmouseout="clearInterval(inter);"> 

</span> 

現在,當我按下按鈕,就開始調用increaseFont功能,但是當我鬆開按鈕,它不會停止或移動鼠標出跨度。如果我將其輸入到瀏覽器控制檯(inter =「setInter ..」和clearInterval(inter);),它會按預期工作。我擔心這與使用html事件時「inter」屬於什麼範圍有關,但我似乎無法找到解決方案。我試過在我的JS的頂部創建一個名爲inter的全局變量(不起作用)。

+0

我將讓他們點擊該按鈕爲每個尺寸更大(或更小)。這個間隔很瘋狂。 –

+0

我也有一個較小的按鈕,但由於增加了0.1 PR點擊,它的範圍從5到140.我不希望他們必須點擊到1350.這就是爲什麼我希望它保持增長的同時按鈕被按下。 –

+0

它似乎在[JSFiddle](http://jsfiddle.net/LL09budf/)上適合我。正如你所說,它可能與'inter'變量的範圍有關,但是我們需要看到更多的代碼 –

回答

0

下面是使用onmousedownonmouseup一個例子(您可能需要使用ontouchstart/ontouchend):

<button type='button' id='bigger'>Bigger</button> 
<button type='button' id='smaller'>Smaller</button> 
<br/> 
<input type='text' id='num' value='5'/> 

window.onload = function ol(){ 
    var bigger = document.getElementById('bigger'), 
     smaller = document.getElementById('smaller'), 
     num = document.getElementById('num'), 
     max_num = 16.0, 
     min_num = 5.0, 
     speed = 30, 
     step = .1, 
     itv; 

    bigger.onmousedown = go_bigger; 
    bigger.onmouseup = reset; 
    smaller.onmousedown = go_smaller; 
    smaller.onmouseup = reset; 

    function reset() { 
     clearInterval(itv); 
    } 

    function go_bigger(){ 
     reset(); 

     itv = setInterval(function o(){ 
      var val = parseFloat(num.value, 10); 

      if (val >= max_num) { 
       reset(); 

       return; 
      } 

      val = Math.round((val + step) * 100)/100; 
      num.value = val; 
      num.style.fontSize = val + 'px'; 
     }, speed); 
    } 

    function go_smaller(){ 
     reset(); 

     itv = setInterval(function o(){ 
      var val = parseFloat(num.value, 10); 

      if (val <= min_num) { 
       reset(); 

       return; 
      } 

      val = Math.round((val - step) * 100)/100; 
      num.value = val; 
      num.style.fontSize = val + 'px'; 
     }, speed); 
    } 
}; 

http://jsfiddle.net/vcbhpzds/