ClearTimeout消除閃動執行個體代碼,cleartimeout執行個體

來源:互聯網
上載者:User

ClearTimeout消除閃動執行個體代碼,cleartimeout執行個體

定義和用法

clearTimeout() 方法可取消由 setTimeout() 方法設定的 timeout。

文法

clearTimeout(id_of_settimeout)

參數 描述
id_of_settimeout 由 setTimeout() 返回的 ID 值。該值標識要取消的順延強制代碼塊。

需求:當滑鼠放到父級菜單上面的時候,顯示下方的子功能表。滑鼠從子功能表或者父級菜單上面移開的時候,子功能表要收合來。最終效果如下:

PS:這樣需求很常見,最常見的做法是li元素下面再嵌套一個Ul元素來包含子項目。這種做法用css就可以完全控制。但今天這個子功能表和導覽列是分開的。即到滑鼠到產品上面的時候顯示header-tags塊。

<ul class="header-nav"><li class="nav-item home"><a href="@Url.Action("Index", "Home")">首頁</a></li><li class="nav-item products" id="header_tags"><a href="#">產品<span class="icon-caret-down"></span></a>....</li></ul><div class="header-tags"><ul><li><img class="screening-img-normal" src="~/Content/static/all.png"><img class="screening-img-hover" src="~/Content/static/all1.png"><p>全部</p></li><li tagid="4"><img class="screening-img-normal" src="~/Content/static/shafa.png"><img class="screening-img-hover" src="~/Content/static/shafa1.png"><p>沙發</p></li><li tagid="3"><img class="screening-img-normal" src="~/Content/static/zuoyi.png"><img class="screening-img-hover" src="~/Content/static/zuoyi1.png"><p>座椅</p></li>....</div> 

這無法用css完全控制(hover只能控制子項目或兄弟元素)。

/*父子*/#a:hover #b{display: block} /*兄弟*/#a:hover + #b{display: block} 

上面的情況就要用指令碼了。這裡涉及到#header_tags和.header-tags兩個元素的移入移出。當滑鼠移入#header_tags,.header-tags顯示,當滑鼠再移入.header-tags的時候不能立即觸發#header_tags的moveout事件,而要保持tags繼續顯示。只有到滑鼠從#header_tags和.header-tags離開後沒有再進入才會把子功能表收合來。

$(function () {var tagsTime;$(document).on('mouseover mouseout', '#header_tags', function(event){var $headerTagsBox = $('.header-tags');if (event.type == 'mouseover') {clearTimeout(tagsTime);$headerTagsBox.slideDown(300);}else if (event.type == 'mouseout') {tagsTime = setTimeout(function(){$headerTagsBox.slideUp(200);}, 200);}});$('.header-tags').hover(function(){clearTimeout(tagsTime);},function(){var $me = $(this);tagsTime = setTimeout(function(){$me.slideUp(200);}, 200);}); });

如果這裡沒有清除定時器和加上延時執行,導覽列就會不斷的閃動。根本無法點擊。

您可能感興趣的文章:
  • js中setTimeout()與clearTimeout()用法執行個體淺析

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.