更改链接的div / id的CSS

时间:2014-06-26 17:57:45

标签: html css css3

我链接到page.html#id这样的页面,因此页面会自动聚焦于此ID。

我如何在CSS中执行此操作,只有URL中带有id的div才会获得黄色背景?

由于

3 个答案:

答案 0 :(得分:6)

使用:target伪选择器。

http://css-tricks.com/on-target/

答案 1 :(得分:0)

编辑 - 不了解:target。答案更好!

您可以侦听hashchange事件,检测当前哈希并将类应用于相应的元素:

window.addEventListener('hashchange', function() {

  // Remove .active from any currently active elements
  var active = document.getElementsByClassName('active');
  for(var i = 0; i < active.length; ++i) {
    active[i].classList.remove('active');
  }

  var id = window.location.hash.substr(1);
  document.getElementById(id).classList.add('active');
});

如果您需要支持browsers that do not support classList,则有很多alternatives

JSFiddle

答案 2 :(得分:0)

获取哈希值并使用JavaScript设置样式:

if(window.location.hash) {
    var hash = window.location.hash.substring(1); //the variable without hash sign.
    document.getElementById(hash).style.background = "yellow";
}
相关问题