一、基礎打印方法
for(var i=1;i<=9;i++){ for(var j=1;j<=i;j++){ document.write(i+"*"+j+"="+i*j+" "); } document.write("
"); }
首先,我們嘗試簡單地使用兩層for循環打印出1-9的乘法表。第一層循環控制行數,第二層循環控制每行輸出的列數。在內層循環中,輸出當前行和列對應的乘積。
二、美化乘法表
document.write('
'+j+"*"+i+"="+i*j+' | '); } document.write('
在這個版本中,我們將乘法表放入一個HTML table標籤中。為了方便美化,我們將列與列之間加入了HTML表格單元格標籤td,並將每一行使用HTML表格行標籤tr括起來。請注意順序,先寫入tr標籤,再寫每個td標籤。
三、使用CSS美化乘法表
table{ border-collapse: collapse; /*去掉邊框*/ } td{ width: 100px; height: 30px; text-align: center; vertical-align:middle; border: 1px solid black; } td:nth-child(odd){ /*奇數列單元格*/ background-color: #f2f2f2; } <script> document.write('<table>'); for(var i=1;i<=9;i++){ document.write('<tr>'); for(var j=1;j<=i;j++){ document.write('<td>'+j+"*"+i+"="+i*j+'</td>'); } document.write('</tr>'); } document.write('</table>'); </script>
在第三個版本中,我們在HTML文件中加入CSS樣式。使用border-collapse: collapse屬性去掉了表格單元格之間的邊框。我們也為表格單元格設置了寬度和高度,以及文字和單元格垂直對齊方式。另外,我們使用了nth-child選擇器,將奇數列的單元格背景色設為灰色,以增強可讀性。
四、使用CSS動畫效果
table{ border-collapse: collapse; /*去掉邊框*/ } td{ width: 100px; height: 30px; text-align: center; vertical-align:middle; border: 1px solid black; transition-duration: 0.5s; } td:hover{ background-color: yellow; /*鼠標懸停時的背景色*/ color: red; transform: scale(1.2,1.2); /*鼠標懸停時單元格放大*/ } td:nth-child(odd){ background-color: #f2f2f2; } table{ margin: auto; /*水平居中*/ } <script> document.write('<table>'); for(var i=1;i<=9;i++){ document.write('<tr>'); for(var j=1;j<=i;j++){ document.write('<td>'+j+"*"+i+"="+i*j+'</td>'); } document.write('</tr>'); } document.write('</table>'); </script>
在第四個版本中,我們使用CSS動畫效果為表格單元格增加互動性。鼠標懸停時,單元格的背景色變成黃色,文字的顏色變成紅色。同時,單元格逐漸放大(scale(1.2,1.2)),創造出彈跳的視覺效果。我們也為整個表格設置了居中對齊,使得乘法表更加美觀。
五、使用jQuery實現動畫效果
table{ border-collapse: collapse; /*去掉邊框*/ } td{ width: 100px; height: 30px; text-align: center; vertical-align:middle; border: 1px solid black; } td:nth-child(odd){ background-color: #f2f2f2; } table{ margin: auto; /*水平居中*/ } <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script> $(document).ready(function(){ $('td').hover(function(){ //鼠標懸停事件 $(this).animate({ backgroundColor:"yellow", color:"red", fontSize:"20px" //放大字體大小 }, 500); }, function(){ //離開事件 $(this).animate({ backgroundColor:"#ffffff", color:"#000000", fontSize:"16px" //恢復字體大小 }, 500); }); var $table = $('<table>'); for(var i=1;i<=9;i++){ var $tr = $('<tr>'); for(var j=1;j<=i;j++){ var $td = $('<td>').text(j+"*"+i+"="+i*j); $tr.append($td); } $table.append($tr); } $('body').append($table); //追加到body中 }); </script>
在第五個版本中,我們使用jQuery庫來完全改寫乘法表的實現。首先使用jQuery庫處理鼠標懸停的事件,通過調整CSS中的屬性漸變地調整表格單元格的顏色和字體大小。然後,我們使用jQuery庫創建並操作HTML元素,替代了原有的document.write方法。最後,將創建的表格追加到body中。這種方法在單頁面應用或開發過程中更為實用。
原創文章,作者:UJLSS,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/369964.html