這段代碼應(yīng)該做的是:我有一個(gè)元素 ID 列表,每個(gè)目標(biāo)元素都包含其他元素。當(dāng)我使用鼠標(biāo)滾輪并且光標(biāo)位于目標(biāo)元素之一(或其某些子元素)上時(shí),必須執(zhí)行某些操作。我寫了這段代碼并且運(yùn)行良好。讓我擔(dān)心的是,每次代碼都必須執(zhí)行許多計(jì)算才能完成任務(wù)。如果有人知道我如何優(yōu)化這項(xiàng)任務(wù),我將很樂意分享。提前致謝。請?jiān)谡麄€(gè)頁面上運(yùn)行代碼片段var flag = true;var myTarget;var myRes;var myI;// The IDs of the target elementsvar array = ['elOne', 'elTwo', 'elThree'];var newArray = array.reverse();for (var i = 0; i < array.length; i++) { var myEl = document.getElementById(array[i]); myEl.parentElement.addEventListener("wheel", event => { mouseWeel(event.target); });}function mouseWeel(cmp) { if (cmp !== myTarget) { for (var i = 0; i < newArray.length; i++) { var res = cmp.closest('#' + newArray[i]); if (res) { break; } } myTarget = cmp; myRes = res; myI = i; } cmd = myTarget; res = myRes; i = myI; if (flag) { var myEl = document.getElementById(newArray[i]); myEl.appendChild(document.createTextNode(i)); flag = false; } else { flag = true; }}<div id="elOne" style="width:100%; height:90vh; background:orangered;"> <div id="elTwo" style="width:50%; height:45%; background:orange; margin: auto;"> <div style="width:80%; height:50%; background:orange; padding: 10px;"> <h2>Lorem ipsum</h2> <span>Lorem ipsum dolor sit amet consectetur.</span> </div> </div> <div id="elThree" style="width:50%; height:45%; background:blue; margin: auto;"> <div style="width:80%; height:50%; background:blue; padding: 10px;"> <h2>Lorem ipsum</h2> <span>Lorem ipsum dolor sit amet consectetur</span> <div style="width: 150px; height: 150px; margin-left: -200px; background:blue; padding: 20px; transform: rotate(-45deg); opacity: 0.5; color: white;"> I am a child of the blue element </div> </div> </div></div>
執(zhí)行鼠標(biāo)“onwheel事件”時(shí)檢測目標(biāo)父元素
慕標(biāo)琳琳
2023-10-20 16:51:23