简体   繁体   中英

parseInt() error: invalid argument

I get a javascript error "invalid arguement" when I use parseInt(). What am i doing wrong?

The function is to increase the font size of every element on a frame by 1

<script>
   var sizeCounter = 1;
    function changeFontSize(){
        //var elements = parent.main.document.getElementsByTagName
        var myElements = parent.main.document.getElementsByTagName('*')

        for (i=0;i<myElements.length;i++){
                if(myElements[i].style.fontSize != null){       
                        var elmFontSize = myElements[i].style.fontSize + "";
                        elmFontSize.replace("px","");

                        if(elmFontSize != "") {
                            var elmFontSizeNum = parseInt(elmFontSize);

                        }
                            var resultSize = elmFontSizeNum + sizeCounter;

                            myElements[i].style.fontSize = resultSize + "px";


                        //alert(myElements[i].className)
                    }
                    sizeCounter++;
            }
    }


</script>

There's a lot wrong. Here's a suggestion for simplifying/rewriting your function:

function changeFontSize(sizeCounter){
 sizeCounter = sizeCounter || 1;
 var myElements = document.getElementsByTagName('*'), currentFontSize = 0;
 for (i=0;i<myElements.length;i++){
  var fsNow = getStyle(myElements[i],'font-size');
  if (fsNow){
   currentFontSize = Number(fsNow.replace(/[^\d]/g,''));
   myElements[i].style.fontSize = (currentFontSize + sizeCounter) + 'px';
  }
 }
}

Where getStyle is:

function getStyle(el,styleProp)
{
  el = /string/i.test(typeof el) ? document.getElementById(el) : el;
  if (!el){return null;}
  var result;
  if (el.currentStyle){
    return el.currentStyle[styleProp];
  }
  else if (window.getComputedStyle){
    return document.defaultView.getComputedStyle(el,null)
           .getPropertyValue(styleProp);
  }
  return null;
}

See this jsfiddle

parseInt takes a string as first parameter, you may want to make sure that elmFontSize is actually a string using typeof(elmFontSize) . If it's not a string, you can transform it into a string before calling the parseInt function.

You only handle "px" and fontsize isn't necessarily a "px" value. If it is for example "em" then parseInt will fail because it is trying to convert a non number value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM