@@ -233,8 +233,43 @@ <h2>Cool</h2>
233233  </ style > 
234234
235235  < script > 
236+     const  triggers  =  document . querySelectorAll ( '.cool > li' ) ; 
237+     const  background  =  document . querySelector ( '.dropdownBackground' ) ; 
238+     const  nav  =  document . querySelector ( '.top' ) ; 
239+ 
240+     function  handleEnter ( )  { 
241+       this . classList . add ( 'trigger-enter' ) ; 
242+       // 有 trigger-enter class 才觸發後面的程式碼 
243+       setTimeout ( ( )  =>  {  this . classList . contains ( 'trigger-enter' )  &&  this . classList . add ( 'trigger-enter-active' ) ;  } ,  150 ) ; 
244+       background . classList . add ( 'open' ) ; 
245+ 
246+       const  dropdown  =  this . querySelector ( '.dropdown' ) ; 
247+       const  dropdownCoords  =  dropdown . getBoundingClientRect ( ) ; 
248+       // 為了減去 nav 元素上面的元素所佔的位置,所以也要取到 nav 的位置並減掉它 
249+       const  navCoords  =  nav . getBoundingClientRect ( ) ; 
250+ 
251+       const  coords  =  { 
252+         width : dropdownCoords . width , 
253+         height : dropdownCoords . height , 
254+         top : dropdownCoords . top  -  navCoords . top , 
255+         left : dropdownCoords . left  -  navCoords . left 
256+       } 
257+ 
258+       background . style . setProperty ( 'width' ,  `${ coords . width }  px` ) ; 
259+       background . style . setProperty ( 'height' ,  `${ coords . height }  px` ) ; 
260+       // translate(x, y) 
261+       background . style . setProperty ( 'transform' ,  `translate(${ coords . left }  px, ${ coords . top }  px)` ) ; 
262+     } 
263+ 
264+     function  handleLeave ( )  { 
265+       this . classList . remove ( 'trigger-enter' ,  'trigger-enter-active' ) ; 
266+       background . classList . remove ( 'open' ) ; 
267+     } 
268+ 
269+     triggers . forEach ( trigger  =>  trigger . addEventListener ( 'mouseenter' ,  handleEnter ) ) ; 
270+     triggers . forEach ( trigger  =>  trigger . addEventListener ( 'mouseleave' ,  handleLeave ) ) ; 
236271  </ script > 
237272
238273</ body > 
239274
240- </ html > 
275+ </ html > 
0 commit comments