導航菜單筆記二

js 給多個li循環添加點擊事件

<ul>
  <li><a class="on" href="#">首   頁</a></li>
  <li><a href="#">新聞快訊</a></li>
  <li><a href="#">產品展示</a></li>
  <li><a href="#">售後服務</a></li>
  <li><a href="#">聯繫我們</a></li>
</ul>

方式一

使用循環

window.onload = function() {
			let aLable = document.getElementsByTagName('a');
			for (let i = 0; i < aLable.length; i++) {
				aLable[i].onmouseover = function() {  // 這寫法不好
					clearInterval(this.time); //不做清除,動畫會累加
					let This = this; //把當前this傳進來
					This.time = setInterval(function() {
						This.style.width = This.offsetWidth + 8 + 'px';
						if (This.offsetWidth >= 160) {
							clearInterval(This.time);
						}
					}, 30);
				}
			}
		}

方便,但是效率不好

方式二

事件代理

利用 target.nodeName判斷(原理可參考文章 https://www.cnblogs.com/liugang-vip/p/5616484.html

window.onload = function() {
			let aLable = document.getElementsByTagName('ul');
			aLable[0].onmouseover  = function(e) {
				let event = e || window.event;
		        let target = event.target || event.srcElement; //標準瀏覽器用event.target,IE瀏覽器用event.srcElement,此時只是獲取了當前節點的位置
		        if (target.nodeName.toLowerCase() === 'a') {
		            clearInterval(target.time); //不做清除,動畫會累加
					let This = target; //把當前this傳進來
					This.time = setInterval(function() {
						This.style.width = This.offsetWidth + 8 + 'px';
						if (This.offsetWidth >= 160) {
							clearInterval(This.time);
						}
					}, 30);
		       	}
    	}

源碼地址

https://github.com/wxygoing/firstTimeTest/blob/master/NavigationMenu/navmenu-horizontal-%E4%BC%B8%E7%BC%A9%E8%8F%9C%E5%8D%95-%E6%B0%B4%E5%B9%B3%E6%96%B9%E5%90%91.html

https://github.com/wxygoing/firstTimeTest/blob/master/NavigationMenu/navmenu-horizontal-%E4%BC%B8%E7%BC%A9%E8%8F%9C%E5%8D%95-%E6%B0%B4%E5%B9%B3%E6%96%B9%E5%90%91-%E6%94%B9%E8%BF%9B.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章