简体   繁体   中英

CSS. Changing image visited link

I have a image-hyperlink. And I want to change the image when the link have status visited. Could you show me how to do it? Preferably without using JavaScript.

I'm trying to do the following: I joined both my images in single common image and here is my code:

<a href="#" class="mylink">
   <img src="common_image.jpg" width="240px" height="240px"/>
</a>

And my styles:

    .mylink {
        width: 120px;
        height: 240px;
        display: block;
        overflow: hidden;
    }

    .mylink:visited img {
        margin-left: -120px;
    }

You cannot alter the src -attribute of an image throught CSS. If it, for some reason, have to be an img-element , then you are stuck with JavaScript for the alteration.

The other alternative would be to get rid of the img -element and use only the anchor with a background instead. The background -property can be controlled through CSS.

Here is a simple example of how to do it for :hover , but in you case :hover could just as easy be changed to :visited instead.

If you place the "visited"-image below the default image in a file called sprite.png, the code would be:

a.mylink {
    width: 120px;
    height: 240px;
    display: block;
    overflow: hidden;
    background: url(sprite.png) no-repeat;
}

a:visited.mylink {
    background-position: 0 -240px;
}

See it live here: http://jsfiddle.net/5ZzkY/ (Uses background-color instead of image for simplicity)

Playing with :visited pseudo selector for background image don't work. There is a security limitation in major browsers to prevent snifing exploit. See this StackOverflow question

You could remove the image and control the background through the css

.mylink {
    background:url('myimagepath-01.jpg') top left no-repeat;
    width: 120px;
    height: 240px;
    display: block;
    overflow: hidden;
}

.mylink:visited {
    background:url('myimagepath-02.jpg') top left no-repeat;  
}

You could try this:

HTML:

<a href="http://google.com" class="image">Link</a>​

CSS:

.image {
    background: transparent url('http://javascript.info/files/tutorial/browser/events/rollover-sprite/button.png') no-repeat top left;
    width: 186px;
    height: 52px;
    display: block;
    text-indent: -9999px;
}
.image:hover {
    background-position: 0 -52px;
}
.image:visited {
    background-position: 0 -104px;
}

If you want to use sprites, then you should set the image as a css background, and move its position using the background-position property. You can see an example in this fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM