2015-10-05 153 views
6

如何在點擊其他鏈接時將超鏈接顏色更改回原始顏色?超鏈接是針對同一頁面的。更改超鏈接顏色,同時點擊其他超鏈接

請從上面的例子可以看到,當點擊蘋果然後單擊葡萄/香蕉..兩者都成爲相同的顏色,因爲(訪問)檢查這個DEMO

。如何使它只有1種顏色(綠色)任一鏈接被點擊

+2

你可以使用'一:積極{顏色:綠色}',繼續參觀 – Fahad

+1

藍你不能用CSS做完全純粹的,最好的,如果你重定向目標就可以得到與點擊元素相同。 [像這樣](http://jsfiddle.net/9ncnrwxq/7/),儘管你失去了移動到目標位置的功能。否則,你需要使用JavaScript。 –

回答

2

時,您可以使用jQuery

$('body a:link').click(function() 
 
{ 
 
\t $('body a').removeClass('active'); 
 
\t $(this).addClass('active'); \t 
 
});
a:link { 
 
    color: blue; 
 
} 
 

 
/* visited link */ 
 
a.active { 
 
    color: green; 
 
} 
 

 
/* mouse over link */ 
 
a:hover { 
 
    color: red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a class="fruit" href="#apple">apple</a></span> 
 
<a class="fruit" href="#grape">grape</a></span> 
 
<a class="fruit" href="#banana">banana</a></span> 
 
<div style="height:500px"></div> 
 
<a name="apple"> apple here</a> 
 
<a name="grape"> grape here</a> 
 
<a name="banana"> banana here</a>

+1

除jQuery之外的其他方法? – user3835327

+0

我認爲在CSS中沒有比jQuery更好的解決方案,但是在CSS中:active和':focus'選擇器給我們提供了一個有限的解決方案。 –

1

做到這一點當你定義所有4個狀態,你應該按以下順序定義它們:

  1. 鏈接
  2. 訪問
  3. 哈弗
  4. 活動

這解決你的問題的一半。

a:link { color: blue; } 
a:visited { color: blue; } 
a:hover { color: red; } 
a:active { color: green; } 

另一半,讓鏈接着色,直到你點擊別的東西,更難。以前點擊過的東西沒有內置狀態,所以讓我們製作一個。

首先,我們需要jQuery來做到這一點,所以讓我們導入它(通過谷歌)。這正好在你的HTML頭:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"> 
</script> 

在jfiddle,你從下拉左邊,而不是選擇的jQuery 2.1.4添加此。

然後,我們可以通過提供這個JavaScript添加一個類的鏈接,如果他們在最後點擊鏈接:

$(function(){ 
    $('a').click(function(){ 
     $('a.lastclicked').removeClass('lastclicked'); //remove class from previous link 
     $(this).addClass('lastclicked'); //add class to newly clicked link 
    }); 
}); 

最後,讓我們調整CSS做着色:

a:link { color: blue; } 
a:visited { color: blue; } 
a:hover { color: red; } 
a:active { color: green; } 
a.lastclicked { color: green; } 

如果您希望將懸停顏色應用到最後點擊的鏈接,則可以添加以下行:

a.lastclicked:hover { color: red; } 


你可以看到所有這些在行動in a Fiddle here

0

試試這個(做複製和粘貼):

的test.html: -

<html> 
<link rel="stylesheet" type="text/css" href="style.css"> 
<a class="fruit" href="#">apple</a></span> 
<a class="fruit" href="#">grape</a></span> 
<a class="fruit" href="#">banana</a></span> 
<div style="height:500px"></div> 
<a name="apple"> apple here</a> 
<a name="grape"> grape here</a> 
<a name="banana"> banana here</a> 
</html> 

風格。CSS: -

a:link{ 
color:blue; 
} 

a:visited{ 
color:purple; 
} 

a:hover{ 
color:orange; 
} 
a:focus{ 
color:green; 
} 

a:active{ 
color:red; 
} 

a:active{ 
color:yellow; 
}