Detect if a link has been clicked and apply a different CSS class if it has

前端 未结 5 1820
轻奢々
轻奢々 2021-01-14 12:53

So what I want to do is determine if the current link is \'active\', i.e. if this link was just clicked by the user.

If it is, then I want to apply the class=s

5条回答
  •  北恋
    北恋 (楼主)
    2021-01-14 13:34

    In current versions of CSS (Not sure if it's CSS 2.1 or CSS3), you should be able to do this:

    li:active { background-color: black; }
    

    However, CSS 2.1 doesn't specify whether li is active when it contains an active a element.

    To be more explicit, you could do this:

    li > a:active { background-color: pink; }
    

    This works in Chrome and Firefox current versions, but apparently not IE7 or IE9. There's no Ruby or JavaScript code required if you can live with that.

    In order to get this to work in IE, you'll likely need to trap an event using JavaScript, which is perhaps more than I have the patience to do, since active links tend to go away pretty fast, as you're generally navigating to a new page when :active becomes relevant. You'd probably bind an onclick event to li's that contain hyperlinks.

    Since you're asking how to do this in Ruby (specifically Sinatra), rather than Rails, the answer is going to depend on how you've structured your project, so it's hard to answer generally enough to be useful; the code will probably not be ruby-specific, other than the question about generating your HTML.

提交回复
热议问题