這一段時間在學習web前端,最近學了jQuery庫,深感其強大,下面通過寫購物車的下拉框做法,把自己的理解和大家交流一下,歡迎各位大神指點指正,廢話不多說,開始正題:
購物車html:
1 <!-- 購物車 start --> 2 <div class="shopping" id="shopping-box"> 3 <a href="" id="shoptext"><i class="iconfont"></i> 購物車(0)</a> 4 <!-- 購物車下拉框 start--> 5 <div class="shop" id="shop-content"> 6 購物車中還沒有商品,趕緊選購吧! 7 </div> 8 <!-- 購物車下拉框 end--> 9 </div> 10 <!-- 購物車 end -->
剛開始學習原生js時候的寫法:
1 //購物車下拉框 start
2 var shoppingBoxNode = document.getElementById("shopping-box");
3 var shopContentNode = document.getElementById("shop-content");
4 var shoptext = document.getElementById("shoptext");
5 shoppingBoxNode.onmouseenter = function{
6 shoptext.style.background = "#fff";
7 shoptext.style.color = "#ff6700";
8 shopContentNode.style.display = "block";
9 console.log("over");
10 };
11 shoppingBoxNode.onmouseleave = function{
12 shoptext.style.background = "";
13 shoptext.style.color = "";
14 shopContentNode.style.display = "";
15 console.log("out");
16 };
17 //購物車下拉框 end感覺很麻煩,而且還不好理解,下面用jQuery來寫的:
1 //購物車 下拉
2 var interval1;
3 $("#shopping-box").mouseenter(function{
4 clearTimeout(interval1);
5 $(this).children.first.css({"color":"#ff6700","background":"#fff"});
6 $(this).children.last.stop(true,true).slideDown;
7 }).mouseleave(function{
8 var self = $(this);
9 interval1 = setTimeout(function{
10 self.children.first.removeAttr("style");
11 },700);
12 $(this).children.last.delay(200).slideUp;
13 });這個看着就乾淨利落的多,相對的減少了代碼量,這裏面事件使用應用鏈的寫法,而且jQuery的方法的兼容問題基本上在其內被都已經被解決了,這點真是讓前端的工作量減少了很多,用原生的時候調兼容調的頭都快炸了(大家都懂的。。。),裏面用到了jQuery中的延時delay和停止動畫stop來處理(很好用的兩個函數),當鼠標移動過快出現的問題
這裏面事件的寫法當然也可以用下面的方法(on也可以用bind來替換):
1 //購物車 下拉
2 var interval1;
3 $("#shopping-box").on({
4 mouseenter:function{
5 }, 6 mouseleave:function{7 } 8 });第一次寫博客,寫的比較亂,也有點也沒有突出重點,望大家見諒,也歡迎大家批評指正,共同進步!
原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/274313.html
微信掃一掃
支付寶掃一掃