简体   繁体   中英

How to create click-able CSS sprite with <a> rather than Javascript?

Here is an example of click-able CSS sprite implemented with Javascript:

Live demo here.

HTML:

 <div></div>

CSS:

 div { width: 100px; height: 100px; background-image: url(http://perfectwebtutorials.com/wp-content/uploads/2011/03/spritecss.png); background-position: -300px -100px; } div:hover { background-position: -100px -100px; }

JS:

 $(function() { $('div').click(function() { window.location = "http://google.com"; }); });

Is that possible to achieve the same without Javascript ?

(The only way I can think of is to use <a href="..."> , but how?)

With an <a> element, give it a href and display: inline-block , along with all the other CSS properties you have set.

a {
    display: inline-block;
    width: 100px;
    height: 100px;
    background-image: url(http://perfectwebtutorials.com/wp-content/uploads/2011/03/spritecss.png);
    background-position: -300px -100px;
}
a:hover {
    background-position: -100px -100px;
}

You asked your question in a convoluted way, but the answer is simple:

  • Change the div to an a .
  • Apply display: block to the a .

See: http://jsfiddle.net/65HdK/

<a href="http://google.com/"></a>

a{
    width: 100px;
    height: 100px;
    background-image: url(http://perfectwebtutorials.com/wp-content/uploads/2011/03/spritecss.png);
    background-position: -300px -100px;

    display: block
}
a:hover {
    background-position: -100px -100px;
}

@misha,check the like http://jsfiddle.net/sandeep/t629m/7/

the main thing is that you have to display:block in <a> tag

because <a> is an inline element example:

a {
    width: 100px;
    height: 100px;
    background-image: url(http://perfectwebtutorials.com/wp-content/uploads/2011/03/spritecss.png);
    background-position: -300px -100px;
    display:block;
}
<a href="http://google.com"><div></div></a>

Seems to be working fine. Live demo: http://jsfiddle.net/vuZz4/

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