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>开发者_Python百科
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.
精彩评论