2012-02-25 83 views
2

當你有這樣的網址www.example.com/#signup時,瀏覽器所做的只是將它的視圖集中在ID爲signup的HTML元素上,是嗎?URL中的CSS選擇器

如果以這種方式聚焦,是否可以更改元素的CSS樣式?

例如假設我有一個div元素,ID爲signup,那麼如果我輸入www.example.com,div的背景是白色,如果我輸入www.example.com/#signup它是黃色的。就像「強調」註冊表單一樣。這是可能嗎?

回答

5
:target { background-color: yellow; } 

:target psuedo-class正是這樣做的。

+0

不錯......這款產品是否適用於舊版瀏覽器? – federicot 2012-02-25 08:41:05

+0

我不確定。說實話,可能不會,但可以通過JS來補救:var a = document.getElementById(location.hash.substr(1));如果(a)a.style.backgroundColor ='黃色';' – 2012-02-25 08:42:14

+0

@John Doe:不是IE8和更老的。 – BoltClock 2012-02-25 14:45:02

1

當頁面加載並應用相應的css類時,您可以閱讀window.location.hash屬性。類似於:

<script type='text/javascript> 
function init(){ 
    var hash = window.location.hash.substr(1); 
    var element = document.getElementById(hash); 
    if(element){ 
     element.className += " emphasize"; 
    } 
} 
</script> 

<body onload="init()"> 
... 
</body> 
+0

謝謝,我會嘗試 – federicot 2012-02-25 09:05:23