javascript實現輸出指定行數的正方形圖案:點擊生成圖案,會有2個提示框,1,輸入圖案的組成字符,只能是1個字符哦2,輸入正方形行數,路過大於10,會設置爲10行數
效果圖:
1.圖案字符:+,行數:5
2.圖案字符:s 行數:10
html文件:
<!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>