📅  最后修改于: 2023-12-03 15:33:36.728000             🧑  作者: Mango
在网页中,常常需要使用一些动态效果来增强用户体验。本文将介绍如何使用PHP代码实现带有背景淡入淡出的div效果。
<div class="bg-fade">
<h1>Hello World!</h1>
<p>Welcome to my website!</p>
</div>
.bg-fade {
opacity: 0;
transition: opacity 1s ease-in-out;
}
window.onload = function () {
var bgFade = document.querySelector('.bg-fade');
var colors = [
'#F44336', '#E91E63', '#9C27B0', '#673AB7',
'#3F51B5', '#2196F3', '#03A9F4', '#00BCD4',
'#009688', '#4CAF50', '#8BC34A', '#FF5722'
];
var randColor = colors[Math.floor(Math.random() * colors.length)];
bgFade.style.backgroundColor = randColor;
bgFade.style.opacity = 1;
};
<?php
header("Content-type: text/javascript");
$colors = [
'#F44336', '#E91E63', '#9C27B0', '#673AB7',
'#3F51B5', '#2196F3', '#03A9F4', '#00BCD4',
'#009688', '#4CAF50', '#8BC34A', '#FF5722'
];
$randColor = $colors[array_rand($colors, 1)];
?>
<script src="bg-fade.php"></script>
<script type="text/javascript">
var randColor = "<?php echo $randColor; ?>";
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP代码实现带有背景淡入淡出的div</title>
<style>
.bg-fade {
opacity: 0;
transition: opacity 1s ease-in-out;
}
</style>
</head>
<body>
<div class="bg-fade">
<h1>Hello World!</h1>
<p>Welcome to my website!</p>
</div>
<script src="bg-fade.php"></script>
<script type="text/javascript">
var randColor = "<?php echo $randColor; ?>";
window.onload = function () {
var bgFade = document.querySelector('.bg-fade');
bgFade.style.backgroundColor = randColor;
bgFade.style.opacity = 1;
};
</script>
</body>
</html>
<?php
header("Content-type: text/javascript");
$colors = [
'#F44336', '#E91E63', '#9C27B0', '#673AB7',
'#3F51B5', '#2196F3', '#03A9F4', '#00BCD4',
'#009688', '#4CAF50', '#8BC34A', '#FF5722'
];
$randColor = $colors[array_rand($colors, 1)];
?>
本文介绍了如何使用PHP和Javascript实现一个背景淡入淡出的div效果,让网页更加动态。这种效果可以用于网站的首页、登录页面、元素加载等等。需要注意的是,本文只是讲解原理,具体实现方式可能会因具体需求而异。