CSS selector in the URL

2019-07-21 16:26发布

When you have a url like this www.example.com/#signup, what the browser does is just to focus it's view on the HTML element with id signup, is that right?

Is it possible to change the element's CSS style if it's focused in that way?

E.g. let's say I have a div element, with the id signup, then if I enter www.example.com, the div's background is white and if I enter www.example.com/#signup it's yellow. Like "emphasizing" the sign up form. Is this at all possible?

2条回答
Animai°情兽
2楼-- · 2019-07-21 16:59
:target { background-color: yellow; }

The :target psuedo-class does exactly this.

查看更多
闹够了就滚
3楼-- · 2019-07-21 17:03

You can read the window.location.hash property when the page loads and apply the corresponding css classs. Something like:

<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>
查看更多
登录 后发表回答