要實現的點贊功能比較簡單,就是實現點擊按鈕,有心向上飄,一直飄出屏幕外。
首先只需要在body中定義一個button。和盛放心的盒子
<div id = "demo"></div><input type = "button" id = "btn1" value = "點個贊吧" />
由于還要引進心的圖片,所以在這里我們在設置css樣式的時候還要設置圖片img的樣式。
css代碼如下:
<style type="text/css"> *{ margin: 0px; padding: 0px; } #btn1{ position: absolute; bottom:100px; width: 200px; background-color: lightblue; font-size: 18px; left:45%; } img{ bottom:100px; margin-left: -15px; width: 20px; height:20px; position: absolute; left: 50%; } </style>下來就是要寫jquery函數。
(document).ready(function(){ // 1. 首先給按鈕綁定點擊事件。(“#btn1”).click(function(){ //2. 生成彩色的心,即隨機選擇圖片。 // 2.1 生成隨機數 var num = Math.floor(Math.random() * 3 +1); //2.2 生成一個img元素,并為其添加src屬性 var image = $(“”);//三個圖片的名字分別是 1.png/2.png/3.png,所以img的路徑和圖片名可以進行線面的字符串拼接 image.attr(“src”,”./images/”+num+”.png”);//3。將生成的img追加到頁面上$(“#demo”).append(image);//4. 下來就是讓心動起來。從點擊按鈕的地方向上飄。利用jquery的動畫函數animate()//生成隨機的距離左邊的距離,這樣就可以使心有種向上飄的感覺 var left = Math.random() * 800;image.animate({ ‘bottom':'800px', ‘left':left, ‘opacity':'0' },3000); });}); });效果圖如下:


以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答