第十六节 jQuery使用offset制作加入购物车动画

 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 <script type="text/javascript" src="../jquery-1.12.4.min.js"></script> 7 <script type="text/javascript"> 8  $(function(){ 9 var $btn = $(#btn);10 var $chart = $(.chart);11 var $countadd = $(.chart em);12 var $point = $(.point);13 14 var $w01 = $btn.outerWidth();15 var $h01 = $btn.outerHeight();16 17 var $w02 = $chart.outerWidth();18 var $h02 = $chart.outerHeight();19 20  $btn.click(function(){21 var oPos01 = $btn.offset();22 var oPos02 = $chart.offset();23 24  $point.css({left:oPos01.left+parseInt($w01/2)-5,‘top‘:oPos01.top+parseInt($h01/2)-5});25  $point.show();26  $point.animate({left:oPos02.left+parseInt($w02/2)-5,‘top‘:oPos02.top+parseInt($h02/2)-5},2000,function(){27  $point.hide();28 var iNum = $countadd.html(); // 获取em元素内的内容29  $countadd.html(parseInt(iNum)+1); // 往em元素写入内容30  });31 32 33  });34  });35 </script>36 <style type="text/css">37  .chart{38  height: 100px;39  width: 100px;40  background-color: gold;41  text-align: center;42  line-height: 100px;43  float: right;44 }45  .chart em{46  font-style: normal;47  color: red;48  font-weight: bold;49 }50  #btn{51  height: 30px;52  width: 200px;53  outline: none;54  float: left;55  margin: 300px auto 0;56 57 }58  .point{59  height: 10px;60  width: 10px;61  background-color: red;62  position: fixed;63  left: 0;64  top: 0;65  display: none;66  border-radius: 50%;67  z-index: 999;68 }69 </style>70 </head>71 <body>72 <div class="chart">购物车<em>0</em></div>73 <input type="button" name="" value="加入购物车" id="btn">74 <div class="point"></div>75 </body>76 </html>

 

相关文章