我有3页。我已经include("include/header.php)
了HTML网页+导航的开头。当用户在联系人页面上时,导航链接带有下划线text-decoration: underline;
我的问题是:我如何使函数自动更改类 - 当用户转到该页面时.underline
?谢谢!
我的标题.php导航代码
<div class="navigation>
<a href="index.php" class="underline">Home<a> <!-- simulating that the user is on this page -->
<a href="about.php">About me</a>
<a href="contact.php">Contact me!</a>
</div>
我的 css 代码
.underline {
text-decoration: underline;
}
索引处的代码.php 和其他包括标头.php
<?php include("include/header.php") ?>
试试这个:
<?php
function underline($page) {
if (strpos($_SERVER['REQUEST_URI'], $page) !== false) {
echo "underline";
}
}
?>
<div class="navigation>
<a href="index.php" class="<?php underline('index.php'); ?>">Home<a> <!-- simulating that the user is on this page -->
<a href="about.php" class="<?php underline('about.php'); ?>">About me</a>
<a href="contact.php" class="<?php underline('contact.php'); ?>">Contact me!</a>
</div>
就个人而言,我对这类事情采取了完全不同的方法。
首先,为您的链接设置一个页面数组,然后循环访问它们,检查它是否是"当前"页面,并添加相关类。
此技术需要更少的代码来输出给定的链接,并且添加更多页面要简单得多。
<?php
$pages = array(
'Home' => 'index.php',
'About me' => 'about.php',
'Contact me!' => contact.php'
// Now adding pages is easy, just add the relevant parts here
);
?>
<div class="navigation">
<?php
// Loop over each page from the array
foreach($pages AS $title => $page) {
// Set the class depending on which page is current
$class = (strpos($_SERVER['REQUEST_URI'], $page) !== FALSE) ? 'underline' : '';
// Output the link
echo "<a href='{$page}' class='{$class}'>{$title}</a>";
} ?>
</div>
在您的包含/标头.php文件中,使用此...
function is_current($page){
$current = $_SERVER['PHP_SELF'];
if($current == $page){
return ' class="underline"';
}
}
<div class="navigation">
<a href="index.php"<?php echo is_current('index.php'); ?>>Home<a> <!-- simulating that the user is on this page -->
<a href="about.php"<?php echo is_current('about.php'); ?>>About me</a>
<a href="contact.php"<?php echo is_current('contact.php'); ?>>Contact me!</a>
</div>
另一个解决方案:
<?php
function underline($page) {
return (basename(__FILE__) === $page) ? 'class="underline"' : '';
}
?>
<div class="navigation">
<a href="index.php" <?php echo underline('index.php') ?>>Home<a>
<a href="about.php" <?php echo underline('about.php') ?>>About me</a>
<a href="contact.php" <?php echo underline('contact.php') ?>>Contact me!</a>
</div>
你必须
得到请求的url,你可以为此使用$_SERVER['REQUEST_URI']
,你的函数应该看起来像这样
function underlinePage($pageYouWant) {
if ($_SERVER['REQUEST_URI'] == "/".$pageYouWant)) {
return 'underline';
}
}
你像这样调用函数
<div class="navigation>
<a href="index.php" class="<?= underlinePage('index.php'); ?>">Home<a>
<a href="about.php" class="<?= underlinePage('about.php'); ?>">About me</a>
<a href="contact.php" class="<?= underlinePage('contact.php'); ?>">Contact me!</a>
</div>