【问题标题】:CSS selector in the URLURL 中的 CSS 选择器
【发布时间】:2012-02-25 08:37:03
【问题描述】:

当你有一个像 www.example.com/#signup 这样的 url 时,浏览器所做的只是将它的视图集中在 ID 为 signup 的 HTML 元素上,对吗?

如果以这种方式聚焦,是否可以更改元素的 CSS 样式?

例如假设我有一个 div 元素,id 为 signup,然后如果我输入 www.example.com,则 div 的背景是白色的,如果我输入 www.example.com/#signup,它是黄色的。就像“强调”注册表单一样。这有可能吗?

【问题讨论】:

    标签: html css url css-selectors


    【解决方案1】:
    :target { background-color: yellow; }
    

    :target 伪类正是这样做的。

    【讨论】:

    • 我不确定。老实说,可能不会,但这可以通过 JS 来解决:var a = document.getElementById(location.hash.substr(1)); if( a) a.style.backgroundColor = 'yellow';
    • @John Doe:不是 IE8 和更早版本。
    【解决方案2】:

    您可以在页面加载时读取window.location.hash 属性并应用相应的css 类。比如:

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

    【讨论】:

      猜你喜欢
      • 2013-06-21
      • 1970-01-01
      • 2013-11-27
      • 2012-02-18
      • 2022-01-22
      • 2018-12-04
      • 1970-01-01
      • 2017-07-05
      • 1970-01-01
      相关资源
      最近更新 更多