這一段時間在學習web前端,最近學了jQuery庫,深感其強大,下面通過寫購物車的下拉框做法,把自己的理解和大家交流一下,歡迎各位大神指點指正,廢話不多說,開始正題:
購物車html:
<!-- 購物車 start -->
<div class="shopping" id="shopping-box">
<a href="" id="shoptext"><i class="iconfont"></i> 購物車(0)</a>
<!-- 購物車下拉框 start-->
<div class="shop" id="shop-content">
購物車中還沒有商品,趕緊選購吧!
</div>
<!-- 購物車下拉框 end-->
</div>
<!-- 購物車 end -->
剛開始學習原生js時候的寫法:
//購物車下拉框 start
var shoppingBoxNode = document.getElementById("shopping-box");
var shopContentNode = document.getElementById("shop-content");
var shoptext = document.getElementById("shoptext");
shoppingBoxNode.onmouseenter = function(){
shoptext.style.background = "#fff";
shoptext.style.color = "#ff6700";
shopContentNode.style.display = "block";
console.log("over");
};
shoppingBoxNode.onmouseleave = function(){
shoptext.style.background = "";
shoptext.style.color = "";
shopContentNode.style.display = "";
console.log("out");
};
//購物車下拉框 end
感覺很麻煩,而且還不好理解,下面用jQuery來寫的:
//購物車 下拉
var interval1;
$("#shopping-box").mouseenter(function(){
clearTimeout(interval1);
$(this).children().first().css({"color":"#ff6700","background":"#fff"});
$(this).children().last().stop(true,true).slideDown();
}).mouseleave(function(){
var self = $(this);
interval1 = setTimeout(function(){
self.children().first().removeAttr("style");
},700);
$(this).children().last().delay(200).slideUp();
});
這個看著就干凈利落的多,相對的減少了代碼量,這里面事件使用應用鏈的寫法,而且jQuery的方法的兼容問題基本上在其內(nèi)被都已經(jīng)被解決了,這點真是讓前端的工作量減少了很多,用原生的時候調(diào)兼容調(diào)的頭都快炸了(大家都懂的。。。),里面用到了jQuery中的延時delay和停止動畫stop來處理(很好用的兩個函數(shù)),當鼠標移動過快出現(xiàn)的問題
這里面事件的寫法當然也可以用下面的方法(on也可以用bind來替換):
//購物車 下拉
var interval1;
$("#shopping-box").on({
mouseenter:function(){
},
mouseleave:function(){
}
});
以上所述是小編給大家介紹的jQuery實現(xiàn)鼠標經(jīng)過購物車出現(xiàn)下拉框 ,希望對大家有所幫助