我需要用PHP创建一个按钮。第五次按下时应该随机改变我的背景颜色并保持每五次按下它的颜色。再按5次后,我的背景颜色应该再次改变并保持到下一次按下
这是我的代码
<?php
session_start();
$_SESSION['counter'] = isset($_SESSION['counter']) ? $_SESSION['counter'] : 0;
if($_POST['sub']) {
$_SESSION['counter']++;
echo "<br/>";
echo $culoare;
echo "<body bgcolor='<?phpecho $culoare;?>'></body>";
}
?>
</head>
<body >
<form action='' method="post">
<input type="submit" name="sub" value="click" />
<input type="hidden" name="counter" value="<?php print $_POST['counter']; ?>" />
</form>
</body>
答案 0 :(得分:0)
有什么问题?你有代码。
提交表单后,在隐藏字段中获取计数器的值。如果该值不等于5,则将其递增并再次将其传递给视图以将其存储为隐藏字段。当值等于5时,更改背景颜色并将计数器设置为0.
如果您想要五次使用相同的颜色,则需要将颜色保留在隐藏字段中。
<?php
// First call.
if(!isset($_POST)) {
$color = "rgb(" . rand(0, 255) . "," . rand(0,255) . "," . rand(0,255) . ")";
$counter = 0;
}
else {
$color = $_POST['color'];
$counter = $_POST['counter'];
}
if($counter == 5) {
$color = "rgb(" . rand(0, 255) . "," . rand(0,255) . "," . rand(0,255) . ")";
$counter = 1; // Set to 1 if you want to change bg color on fifth click.
}
else {
$counter++;
}
?>
<div style="background-color: <?php echo $color; ?>">
<form method="post">
<input type="hidden" name="color" value="<?php echo $color; ?>" />
<input type="hidden" name="counter" value="<?php echo $counter; ?>" />
<input type="submit" value="Submit" />
</form>
</div>
我认为这样的事情可能有用。