我目前正在学习一个初级PHP编程课程,我需要一些帮助来完成我正在尝试解决的一项作业。 分配是创建一个表单,用户可以在其中输入正整数。 然后,使用"for"循环显示由"hr"标签[提示:<hr size=1 width=50% color='black'>
]创建的水平线数量。最后,使用 if 语句执行"模数"计算。当"for"循环中的计数器是偶数时,将水平线的宽度设置为50%;否则,将水平线的宽度设置为 100%。
这是我到目前为止想出的代码:
<?php
if ($_POST) { // if the form is filled out
$integer = $_POST["pi"];
$i = $integer;
for ($i = 1; $i <= $integer; $i++) {
if ($i % 2) { // modulus operator
echo "<hr size=1 width=50% color='black'>";
} else {
echo "<hr size=1 width=100% color='red'>";
}
}
}
else { // otherwise display the form
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Enter a <i>Positive Integer</i>:
<input type="text" name="pi" size=5>
<input type="submit" value="Check"></form></p>
<?php
}
?>
我还不能发布图像,但示例输出应该是 50% 的黑色水平规则,然后是 100% 的红色水平规则,直到达到输入的整数。在每个小时之间似乎有一些间距。
这一行:
$i = $integer;
。是多余的,只要你说for($i = ...
,$i就会被覆盖。在您的情况下,应该是这样。把那条线拿出来。
其次,我认为你遇到的问题是你的线条没有显示为黑色或红色。原因是color
是一个字体属性,你应该看看这篇文章来了解如何改变你的颜色:更改 hr 元素的颜色
我建议在PHP中使用class='black'
和class='red'
,并在CSS中设置类。
目前尚不清楚问题是什么。如果问题是您的 HR 元素之间有空格,那么删除默认边距会有所帮助(至少在 Firefox 中,我不确定是否所有浏览器都在 HR 上使用相同的渲染规则(。
<hr size="1" width=50% color='black' style="margin:0;" />
<hr size="1" width=100% color='red' style="margin:0;" />
问题是您$i赋值等于变量 $integer,因此它们是相同的值。
<?php
if ($_POST)
{ // if the form is filled out
$integer = $_POST["pi"];
for ($i = 1; $i <= $integer; $i++)
{
if ($i % 2 ===0)
{ // modulus operator
echo "<hr size=1 width=50% color='black'>";
}
else
{
echo "<hr size=1 width=100% color='red'>";
}
}
}
else
{ // otherwise display the form
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Enter a <i>Positive Integer</i>:
<input type="text" name="pi" size=5>
<input type="submit" value="Check"></form></p>
<?php
}
?>
使用此 CSS 代码格式化所有 hr 元素
<style type="text/css">
hr {margin: 0px auto 0px auto;}
</style>