大家好。最近做一个项目,要求用javascript动态改变img的图象,条件是图象少于height和width限制时按原大小显示,大于height和width限制时则按height和width限制显示。这我的代码
StringBuilder sbShowImage = new StringBuilder();
sbShowImage.Append("function " + ddlImageName.ClientID + "ShowImage(){\n");
sbShowImage.Append(" var ddlControl = document.getElementById(\"" + ddlImageName.ClientID + "\");\n");
sbShowImage.Append(" var height = " + Height.ToString() + ";var width =  " + Width.ToString() + " ;\n");
sbShowImage.Append(" var imgUrl = ddlControl.options[ddlControl.selectedIndex].value;\n");
sbShowImage.Append(" var imgImage = document.getElementById(\"" + imgImage.ClientID + "\");\n");
sbShowImage.Append("    imgImage.style.display = \"inline\";\n" );
sbShowImage.Append("    imgImage.style.height = '';\n" );
sbShowImage.Append("    imgImage.style.width = '';\n" );
sbShowImage.Append("    imgImage.src = imgUrl;\n" );
sbShowImage.Append("    window.alert( \"Your selection is: \" + ddlControl.options[ddlControl.selectedIndex].text );\n" );
sbShowImage.Append("    if( imgImage.getAttribute( \"height\" )>height && imgImage.getAttribute( \"width\" )>width ){ imgImage.style.pixelHeight = height; imgImage.style.pixelWidth = width;}\n" );
sbShowImage.Append("    if( imgImage.clientHeight>height && imgImage.clientWidth>width ){ imgImage.style.pixelHeight = height; imgImage.pixelWidth = width;}\n" );
sbShowImage.Append("}\n");
litJSArray.Text = sbShowImage.ToString();问题是当第一次选择大图片(大于height和width限制)时不是按height和width限制来显示,而是按原尺寸显示。例如,height=100和width=100,图片B.gif高是150宽度是150,每次选择时就应该按高是100宽度是100来显示,但现在第一次选择B.gif却按高是150宽度是150显示以后再选择又按高是100宽度是100来显示。为什么会这样?