0

ここで私はボタンのようなFacebookを作ろうとしています。これが私のコードです:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>like button</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<style>
    #like {
        height: 215px;
        background: url(images/sprite.png) no-repeat;
        background-position: 0px 0px;
    }
</style>
<script type="text/javascript">
    $(document).ready(function(){
        $("#like").click(function(){
            $("#like").css("background-position","0px -225px");
        });
    });
</script>
</head>
<body>
    <div id="like">
    </div>
</body>
</html>

これで、ユーザーがそれをクリックすると画像が変わります。その写真を変更したいのですが、その逆も同様です。どうやって?これを実装する他の完璧な方法はありますか?

4

1 に答える 1

1

Define 2 CSS classes (one for Active state and 2nd for Other state) and have relevant CSS ( load image from the sprite image) . Use those on the button/like image click event. Something like this

CSS

.stateA,.stateB
{
  background-image:url('http://www.wing-co.jp/img/ui/site_skin/default/sprite_facebook.png');
  width:20px;  height:20px;       
}

.stateA
{  
  background-position:-511px -212px;    
}
.stateB
{
  background-position:-498px -212px;    
}

HTML

<input type="button" id="btnLike" class="stateA" value="" />

Javascript

$(function(){

    $("#btnLike").click(function(e){
      e.preventDefault();
      var item=$(this);
      if(item.attr("class")=="stateA")
      {
         item.removeClass("stateA").addClass("stateB");
         //If you want to update database,you can make an ajax call here
      }
      else
      {
         item.removeClass("stateB").addClass("stateA");
         //If you want to update database,you can make an ajax call here
      }
  });   

});

Working Sample : http://jsfiddle.net/cGWTM/32/

于 2012-05-25T17:47:23.640 に答える