昨天剛申請成功JS權限,心血來潮想添加點東西,記得之前看到別人家博客首頁點擊鼠標的時候會出現炫酷的 “小心心”,自己也來搞一個。沒有用jquery啥的框架,原生js寫起來麻煩了點,不過主要是怕博客首頁加載不進去jquery所以先這么着試試,意料之中沒有問題。
畢竟剛開始給自己博客添加JS才疏學淺,有更好的方法添加更炫酷的動態效果可以分享給我呀。有大神給指點指點那就更多謝啦。歡迎指正錯誤~
效果如下:
話不多說了,先添加css代碼,主要是用來畫“小心心”的:
1 body {position: relative;} 2 .img {width: 20px;height: 20px;opacity: 1;position: absolute;z-index: 100000;transition: 1s;} 3 .left,.right {width: 10px;height: 10px;border-radius: 100%;position: absolute;} 4 .right {right: 0;} 5 .under {width: 10px;height: 10px;position: absolute;top: 5px;left: 5px;transform: rotate(45deg)} 6 .text {width: 50px;font-size: 10px;line-height: 1;position: absolute;top: -1em;left: -15px;text-align: center;}
啰嗦幾句,我添加在頁面定制css代碼 那個文本框里面沒有生效,於是乎干脆在側邊欄公告代碼 中添加style標簽后添加css就好了:
1 <style> 2 body{ 3 position:relative; 4 } 5 .img {width: 20px;height: 20px;opacity: 1;position: absolute;z-index: 100000;transition: 1s;} 6 .left,.right {width: 10px;height: 10px;border-radius: 100%;position: absolute;} 7 .right {right: 0;} 8 .under {width: 10px;height: 10px;position: absolute;top: 5px;left: 5px;transform: rotate(45deg)} 9 .text {width: 50px;font-size: 10px;line-height: 1;position: absolute;top: -1em;left: -15px;text-align: center;} 10 </style> 11 <script>
接下來是js:
1 <script> 2 // 點擊出的文字數組,可自行添加,不要太多哦 3 text = ["你好呀~", "點我呀~", "啦啦啦~", "哎呀呀~", "求關注~", "帥哥美女~", "哦~", "咦~"]; 4 // 計數 5 var count = 0; 6 // 鼠標按下事件 7 document.body.onmousedown = function (e) { 8 // 獲取鼠標點擊位置 9 var x = event.pageX - 18; 10 var y = event.pageY - 30; 11 // 分別創建所需要的元素節點 12 var img = document.createElement("div"); 13 var left = document.createElement("div"); 14 var right = document.createElement("div"); 15 var under = document.createElement("div"); 16 var txt = document.createElement("div"); 17 // 通過隨機數從文字數組中獲取隨機下標的文字 18 var textNode = document.createTextNode(text[parseInt(Math.random() * text.length)]); 19 // 文字添加到txt節點中 20 txt.appendChild(textNode); 21 22 img.className = "img" + " " + "img" + count; 23 left.className = "left"; 24 right.className = "right"; 25 under.className = "under"; 26 txt.className = "text"; 27 img.style.top = y + "px"; 28 img.style.left = x + "px"; 29 // 將創建的元素添加到容器中 30 img.appendChild(left); 31 img.appendChild(right); 32 img.appendChild(under); 33 img.appendChild(txt); 34 document.body.appendChild(img); 35 // 獲取隨機顏色 36 var color = "rgb(" + parseInt(Math.random() * 255) + "," + parseInt(Math.random() * 255) + "," + 37 parseInt(Math.random() * 255) + ")"; 38 txt.style.color=color; 39 for (var i = 0; i < 3; i++) { 40 img.children[i].style.background = color; 41 } 42 } 43 // 鼠標抬起事件 44 document.body.onmouseup = function () { 45 document.getElementsByClassName("img" + count)[0].style.transform = "scale(0.5)"; 46 document.getElementsByClassName("img" + count)[0].style.transform = "translateY(-40px)"; 47 document.getElementsByClassName("img" + count)[0].style.opacity = "0"; 48 count++; 49 } 50 </script>
到這就沒了,不過等下,想添加這些東西在你的博客首頁上生效,你得先申請博客園的js權限呀 = =