本文實例講述了javascript實現輸出指定行數正方形圖案的方法。分享給大家供大家參考。具體如下:
javascript實現輸出指定行數的正方形圖案:點擊生成圖案,會有2個提示框,1,輸入圖案的組成字符,只能是1個字符哦2,輸入正方形行數,路過大于10,會設置為10行數
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><html><head><title> 生成正方形 </title><Script type='text/javascript'>//動態測字符的寬度,傳入字符,放在span,判斷寬度變化,返回function get_width(zifu){if(cwidth.innerHTML.length>0)cwidth.innerHTML='';//路過有元素,清空var oldwidth=cwidth.offsetWidth;cwidth.innerHTML=zifu;var zifu_width=cwidth.offsetWidth-oldwidth;cwidth.innerHTML='';//alert(zifu_width);return zifu_width;}//輸出正方形函數function create(){var tuxing=prompt('請輸入圖案,必須1個字符');//圖案,路 a if(tuxing==null||tuxing==''||tuxing.length>1){alert('請輸入圖 案,圖案必須1個字符');return false;}//提示框,輸入行數var count=prompt('請輸入正方形的行數');if(count==null||count==''||count<1||isNaN(count)){alert('您的輸入的行數存在問題,1.不得空2.大于1 3.不得為非數字');return false;}//根據行數,得到一行的字符竄if(count>10){count=10;alert('輸入的行數大于10,自動修改為10');}var hangstr='';for(i=1;i<=count;i++){hangstr+=tuxing+' ';//判斷變長是否超過文檔的if(get_width(hangstr)>maxw-100){alert('過長的行');count=i-1;hangstr=oldhangstr;break;}oldhangstr=hangstr;}//生成圖形字符串var tustr='';//圖形字符串for(i=1;i<=count;i++)tustr+=hangstr+'<br/>';//把圖形字符串放入圖形層zengfang.innerHTML=tustr;}</script> </head> <body> <div id='zengfang'>此處顯示圖形</div> <input type='button' value='生成正方形圖案' onclick='create()'><br><span id='cwidth'></span><!-- 測試獲取字符串的寬度,因為行數過大,會超過文檔范圍,而發生折行<input type='text' value='' id='text1'> <input type='button' value='顯示字符寬度' onclick='get_width(text1.value)'> --> <Script type='text/javascript'> var maxh=document.body.clientHeight;//文檔高 正方形最大長度 var maxw=document.body.clientWidth;//文檔寬,正方形最大長度 //alert(maxh); //alert(maxw); </script> </body></html>
效果圖:
圖案字符:A,行數:5
希望本文所述對大家的javascript程序設計有所幫助。
新聞熱點
疑難解答