使用两个不同的符号生成三角形图案

时间:2017-10-25 06:59:33

标签: javascript html css

我想生成如下的三角形:

a       (1px)
bb      (2px)
aaa     (3px)
bbbb    (4px)

然而,我发现如果两个符号的大小不同,它将不会是三角形。例如,结果将是:

口
xx
口口口
xxxx

这是我的代码:



<html>

<body>
  <script type="text/javascript">
    <!--    

    window.alert("Hello! This website draws a triangular pattern.");
    var height; //the height of the triangular pattern
    var first; //the first symbol that forms the triangle 
    var second; //the second symbol that forms the triangle
    var display;


    height = window.prompt("What is the height of the triangular pattern?")
    first = window.prompt("Please enter a symbol to generate the triangular pattern:")
    second = window.prompt("Please enter another symbol to generate the triangular pattern:")


    h = parseInt(height);

    var i, j;

    for (i = 1; i <= h; i++) {

      display = "<p style = \"font-size: " + i + "ex\">";

      for (j = 1; j <= i; j++) {
        if (i % 2 > 0)
          display += first;

        if (i % 2 <= 0)
          display += second;
      }

      display += "</p>";
      document.write(display);
    }
    //-->
  </script>
</body>

</html>
&#13;
&#13;
&#13;

这是一个在线发现的练习,但我忘记了来源。我只需要使用一个HTML文件来完成任务。我不能使用外部CSS。

简单地说,如果第一行总共使用 a px,那么第二行需要使用 2a px,忽略符号的大小。

我想知道如何才能做到这一点。如下图所示。

enter image description here

我认为如果符号的大小几乎相同,我可以不情愿地生成形状。希望上面的代码不需要改变,如果没有大问题,因为我想保持我的一些努力。

1 个答案:

答案 0 :(得分:1)

将行高设置为1px。将for循环中的第一个语句更改为以下代码

display = "<p style = \"font-size: " + i + "ex; line-height: " + i +"px\">";

你会得到像

这样的东西

enter image description here