问题描述:

Consider the following fiddle: http://jsfiddle.net/GMA76/

On the links active state I want to replace the content of the a tag, then it should continue to follow the link. However when I style it as shown in the fiddle and here:

a div:first-child{

display:block;

}

a div:last-child{

display:none;

}

a:active div:first-child{

display:none;

}

a:active div:last-child{

display:block;

}

The link doesn't work the first time you click it. It only replaces the content and then it seems the redirection fails.

How would I fix that?

网友答案:

Browsers don't take well to content changing on the :active event. Even if it did work, a CSS-only solution would likely mean that the user wouldn't even see the change in content before the new page had loaded (or started to load with a white screen). I tested a lot with the :after pseudo-selector and the content property, but this didn't work either.

And rightly so. Changes to content should only be done with a language like Javascript. This is a logic issue and is outside of the scope of a styling language. Therefore, I would suggest using Javascript.

I've created a quick fiddle here using Javascript with jQuery (doesn't need jQuery it but it's easier) to switch the text in the link and then go to the new page exactly 1 second afterwards. This way you only need to have the original link in the HTML rather than hiding separate links with CSS. There are more flexible and extensible ways to do this if it's not just for one or two links but for the sake of an example, take a look at the fiddle.

This is the jQuery:

$(".switch-link").click(function(){
    $(this).text("Test Two");
    var href = $(this).attr('href');
    setTimeout(function(){
        window.location = href
    }, 1000);
    return false;
});

1000 is the delay between the text changing and the browser starting to load the new page, you can change this to suit your needs.

相关阅读:
Top