2010-10-09 36 views
2

我的菜單是一堆鏈接,然後我用CSS樣式按鈕如何給予了積極的菜單項不同的造型

<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技巧?

回答

1

CSS的:active僞類可用於:

a.mybutton:active { 
    /* rules */ 
} 
3

CSS技巧

#menu a:active { 
    color: #f00; 
} 

同爲:懸停:參觀

好運!

編輯

,現在你希望鏈接你在被風格化不同的頁面看,我需要更多的細節。你使用PHP嗎?你不使用每頁一個PHP腳本?

無論如何,這應該是有效的,如果你有一個header.php文件,你包含在你的所有頁面中,或者你懶得對每個鏈接的類進行硬編碼。

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> 
+0

由於某種原因,這是行不通的。 – vla 2010-10-09 08:35:11

+0

更新了上面的代碼 – Claudiu 2010-10-09 09:34:23

2

假設你的意思是 「當用戶查看與該鏈接對應的頁面」(而不是「當用戶通過鏈接按下鼠標按鈕但尚未釋放它時」):

在鏈接中包含一個類(如current),然後在選擇器中使用它。在將其提供給用戶之前,將該類添加到頁面的HTML中,在服務器端過程中執行此操作通常是最好的方法。

+0

您能給我一個簡單的代碼示例嗎?我是否使用JQuery添加當前類,以及我仍然需要在我的css中使用'#menu a:active {}'這樣的東西? – vla 2010-10-09 08:42:04

+0

正如我所說,它應該完成服務器端。具體取決於您使用的服務器端語言。選擇器將更多地沿着'#menu a.current'的行。 – Quentin 2010-10-09 08:46:10

+0

我現在明白了。我正在考慮同樣的事情,一旦點擊實際指向該頁面,活動狀態就不會持續。那麼我如何有條件地用PHP添加當前類? – vla 2010-10-09 08:48:36