2014-11-25 80 views
0

我有以下代碼:爲什麼在javascript中的元素的寬度沒有增加

它增加了元素的寬度以及減少它。

function _width(ele, size, speed){ 
    ele = document.getElementById(ele); 
    var eleWidth = ele.clientWidth, 

     incInWidth = setInterval(function(){ 

      if (eleWidth<size) { increase();}; 
      if (eleWidth>size) { decrease();}; 
      if (eleWidth=size) { stopInc();}; 
     }, speed), 

     increase = function(){ 
      ele.style.width = eleWidth + ' px'; 
      eleWidth++; 
     }, 

     decrease = function(){ 
      ele.style.width = eleWidth + ' px'; 
      eleWidth--; 
     }, 

     stopInc =function(){ 
      clearInterval(incInWidth); 
     }; 
}; 

當我運行谷歌控制檯上的代碼,則此函數返回undefined。並且沒有錯誤,因爲它不會引發任何錯誤,並且此功能不起作用。

它不會將任何樣式屬性添加到傳遞給上述函數的那個​​元素。這意味着什麼,它根本不會調用increase();,decreasestopInc();子功能,或者如果它確實沒有評估這三個子功能中的第一個語句。

我認爲它應該工作,因爲它更簡單的代碼運行完美,但它不僅增加了寬度:

function c (e,s,v){ 
    var ele = document.getElementById(e), 
    width= ele.clientWidth; 

    var incInWidthOfEle = setInterval(function(){ 

      if (width <= s) { 
        increase(); 
       }else{ 
        stop_(); 
       }; 

      }, v); 

    var increase = function(){ 

      ele.setAttribute('style', 'width:' + width +'px;'); 
      width++ ; 
    }; 

    var stop_ = function(){ 

     clearInterval(incInWidthOfEle); 

    }; 

}; 

我剛剛加入的第一個代碼比第二,如果第二代碼一些更多的功能使用setInterval完美運行,然後使用這種思想,我不會錯誤的在使用setInterval的問題的第一個代碼。

那麼錯誤在哪裏?

+0

在第一種方法是不使用「尺寸」,不應該是什麼? – Hacketo 2014-11-25 10:41:14

+0

對不起,這是輸入錯誤..感謝那 – 2014-11-25 10:43:46

+1

'if(eleWidth = size)'錯誤。 – 2014-11-25 10:44:33

回答

-2

請給我們您的示例電話。你可能誤以爲在這樣的代碼:

if (eleWidth < size) { increase();}; 
if (eleWidth > size) { decrease();}; 
if (eleWidth == size) { stopInc();}; 

編輯: 完整的解決方案:http://jsfiddle.net/2cfdj6z2/

+1

使用意見詢問有關細節,而不是單獨的答案。 – hon2a 2014-11-25 10:48:02

+0

我不能因爲我沒有50的聲望。 – bemol 2014-11-25 10:50:51

+1

然後只是耐心,並回答其他的東西:) – hon2a 2014-11-25 10:51:49

相關問題