如何给活动菜单项不同的样式 [英] How to give active menu item different styling
问题描述
我的菜单是一堆链接,然后我使用CSS来设置为按钮
My menu is a bunch of links which I then use CSS to style as buttons
<div id="menu">
<a href="" class="mybutton">Item 1</a>
<a href="" class="mybutton">Item 3</a>
<a href="" class="mybutton">Item 3</a>
</div>
单击菜单项并激活时,以不同方式设置样式的最佳方法是什么?我是否使用jquery或javascript添加新类?或者有一个CSS技巧吗?
When a menu item is clicked and is active, what's the best way to style it differently? Do I use jquery or javascript to add a new class? or there's a CSS trick for this?
推荐答案
CSS技巧是
#menu a:active {
color: #f00;
}
:hover 和相同:访问
祝你好运!
编辑
现在看到您想要以不同方式设置您所在页面的链接,我需要更多详细信息。你用PHP吗?你不是每页都使用一个PHP脚本吗?
Seeing now that you want the link to the page you're on being styled differently, I need more details. Do you use PHP? Don't you use one php script per page?
无论如何,如果你有一个header.php文件包含在你的所有页面或者你只是懒得为每个链接硬编码类。
Anyway, this should work, in case you have a header.php file that you include in all your pages or you're simply lazy to hard-code the classes for every link.
PHP:
// Return $return if this page is $page, false otherwise
function is_current($page, $return) {
$this_page = $_SERVER['SCRIPT_NAME']; // will return /path/to/file.php
$bits = explode('/',$this_page);
$this_page = $bits[count($bits)-1]; // will return file.php, with parameters if case, like file.php?id=2
$bits = explode('?',$this_page);
$this_script = $bits[0]; // will return file.php, no parameters
return ($page == $this_script?$return:false); // return $return if this is $page, false otherwise
}
CSS
/* blue, no underline when normal */
a {
text-decoration: none;
color: #00f;
}
/* red, underlined when class active */
a.active {
text-decoration: underline;
color: #f00;
}
您的档案
<!-- Simply echo the function result for each link class -->
<a href="home.php" class="<?php echo is_current('home.php','active'); ?>">Home</a>
<a href="about.php" class="<?php echo is_current('about.php','active'); ?>">About</a>
这篇关于如何给活动菜单项不同的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!