简体   繁体   English

单击链接时更改颜色

[英]changing colors when link is clicked

If I have a menu set up in the header which I use for most of my pages as "include/header.php" how do I setup so when I click on a link, it goes to that page, and that link changes colors (and shows as active)? 如果我在标题中设置了一个菜单,我将其用于大多数页面作为“include / header.php”我如何设置,所以当我点击链接时,它会转到该页面,并且该链接会改变颜色(并显示为活动)? Would jquery be good? jquery会好吗? or PHP? 还是PHP?

Thanks! 谢谢!

You could use PHP to add a class to the current button by comparing it's URL, and the current page URL from $_GET . 您可以使用PHP通过比较它的URL和$_GET的当前页面URL将类添加到当前按钮。 Without knowing what your URL structure is like, I can't say much more than that. 在不知道你的网址结构是什么的情况下,我不能说更多。

For example, using an array with button text and URLs: 例如,使用带有按钮文本和URL的数组:

$links = array('Home' => 'home', 'About' => 'about');

foreach($links as $text => $page)
{
    if($_GET['page'] == $page)
    {
        echo '<a href="/index.php?page=' . $page . ' class="current">' . $text . '</a>';
    }
    else
    {
        echo '<a href="/index.php?page=' . $page . '>' . $text . '</a>';
    }
}

This code will add a class of current to the button who's page matches the value in $_GET . 此代码将向按钮添加一类current ,该按钮的页面与$_GET中的值匹配。 This might not exactly fit your needs due to you probably having a different URL structure, among other things, but it gives a basic explanation and example of how to do this. 这可能不完全符合您的需求,因为您可能具有不同的URL结构,但它提供了基本的解释和如何执行此操作的示例。

Use php, you could write a function before your include like so, 使用php,您可以在包含之前编写一个函数,如此

function activeLink ($page) {
    if ($page = 'home') echo ' class="active"';
    elseif ($page = 'about') echo ' class="active"';
    elseif ($page = 'posts') echo ' class="active"';
}

And in your header file, 在你的头文件中,

echo '<a href="#"' . activeLink($page) . '>Home</a>
<a href="#"' . activeLink($page) . '>About</a>
<a href="#"' . activeLink($page) . '>Posts</a>';

And on your actual page; 在你的实际页面上;

$page = 'home';
include('header');

This will do the trick. 这样就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM