学习web前端有一段时间了,最近学了jQuery库,很厉害。在此,我想通过写购物车的下拉框,和大家分享一下我的理解,欢迎大家指出来。废话不多说,言归正传:购物车:1 <!-- 购物车 start -
学习web前端有一段时间了,最近学了jQuery库,很厉害。在此,我想通过写购物车的下拉框,和大家分享一下我的理解,欢迎大家指出来。废话不多说,言归正传:
购物车:
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 delay和stop动画stop来处理鼠标移动过快时的问题。
当然,下面的方法可以用来写这里的事件(on也可以用bind代替):
1 //购物车 下拉 2 var interval1; 3 $("#shopping-box").on({ 4 mouseenter:function{
5 }, 6 mouseleave:function{7 } 8 });
第一次写博客,很乱,没有重点。希望大家见谅,也欢迎大家批评指正,共同进步!