sprite image replacement via link

2019-08-30 07:19发布

I am looking to display a section of my sprite within a div by default, then have a text menu below the div that when different links are clicked, the section of the sprite that is displayed changes.

Here is where I am so far and have gotten my sprites all to display with the following:

INDEX

<html>

<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
<i class="sprite sprite-caramel"></i>
<i class="sprite sprite-chocolate"></i>
<i class="sprite sprite-empty"></i>
<i class="sprite sprite-strawberry"></i>
<i class="sprite sprite-vanilla"></i>
</body>

</html>

CSS

.sprite {
    background-image: url(sprite1.png);
    background-repeat: no-repeat;
    display: block;
}

.sprite-caramel {
    width: 176px;
    height: 250px;
    background-position: 0 0;
}

.sprite-chocolate {
    width: 176px;
    height: 250px;
    background-position: -176px 0;
}

.sprite-empty {
    width: 176px;
    height: 250px;
    background-position: -352px 0;
}

.sprite-strawberry {
    width: 176px;
    height: 250px;
    background-position: -528px 0;
}

.sprite-vanilla {
    width: 176px;
    height: 250px;
    background-position: -704px 0;
}

What I would like to do is display the "empty" by default within a div, then under the div have text links with "chocolate" "vanilla" "strawberry" etc. When the link is clicked, the sprite position would then change to reflect the image of the link clicked.

I only seem to be able to find image replacement on hover when searching with google...

I am 100% new to sprites and have never used them until now.

1条回答
▲ chillily
2楼-- · 2019-08-30 07:58

Seems like you need Javascript to get the job done.

HTML

<body> 
   <div id="tumbler" class="sprite sprite-empty"></div>
   <a class="flavor" data-flavor="caramel" href="#">Caramel</a>
   <a class="flavor" data-flavor="chocolate" href="#">Chocolate</a>
   <a class="flavor" data-flavor="empty" href="#">Empty</a>
   <a class="flavor" data-flavor="strawberry" href="#">Strawberry</a>
   <a class="flavor" data-flavor="vanilla" href="#">Vanilla</a>

CSS

 .sprite {
       background-image: url(http://puu.sh/3orSM.png);
       background-repeat: no-repeat;
       display: block;
       width: 176px;
       height: 250px;
   }
   .sprite-caramel {
       background-position: 0 0;
   }
   .sprite-chocolate {
       background-position: -176px 0;
   }
   .sprite-empty {
       background-position: -352px 0;
   }
   .sprite-strawberry {
       background-position: -528px 0;
   }
   .sprite-vanilla {
       background-position: -704px 0;
   }

Javascript - Requires jQuery

   jQuery(document).on("ready", function() { 
      jQuery('.flavor').bind('click', function(e) {
         jQuery('#tumbler').attr('class', 'sprite sprite-' + jQuery(this).data('flavor'));
            e.stopPropagation();
         });
    });

Demonstration

And of course, the demo.

查看更多
登录 后发表回答