iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 3
0
Modern Web

師父領進門 修行在個人系列 第 18

18–JS挑戰–(13)–Cool Dropdown Navbar + Click & Drag

  • 分享至 

  • xImage
  •  

廢話不多說,繼續努力。

  1. Strip follow alone dropdown
  • 這章很精彩,很多實務上考量以及自己去找出問題在哪,需要在自己做一次會更了解!!
  • 為什麼分別加兩個style? 因為transition 無法同時處理 display opacity
  • setTimeout後續的問題處理 加入條件式
  • cords 要記得考量其他元素對於位置的影響
  const triggers = document.querySelectorAll('.cool > li')
  const background = document.querySelector('.dropdownBackground')
  const nav = document.querySelector('.top')

  function handleEnter() {
    this.classList.add('trigger-enter')
    setTimeout(() => {
      if(this.classList.contains('trigger-enter')){
        this.classList.add('trigger-enter-active')  
      }
      },150);
    background.classList.add('open')

    const dropdown = this.querySelector('.dropdown')
    const navCord = nav.getBoundingClientRect()
    const dropdownCord = dropdown.getBoundingClientRect()

    const cords= {
      height : dropdownCord.height,
      width : dropdownCord.width,
      top : dropdownCord.top - navCord.top,
      left : dropdownCord.left - navCord.left
    }
    background.style.setProperty('width',`${cords.width}px`)
    background.style.setProperty('height',`${cords.height}px`)
    background.style.setProperty('transform',`translate(${cords.left}px, ${cords.top}px)`)
  }

  function handleLeave() {
    this.classList.remove('trigger-enter', 'trigger-enter-active')
    background.classList.remove('open')
  }

  triggers.forEach( trigger => trigger.addEventListener('mouseenter',handleEnter))
  triggers.forEach( trigger => trigger.addEventListener('mouseleave',handleLeave))

  1. Click and drag to scroll
  • mousedown, mouseleave, mouseup, mousemove 的綜合應用
  • 先設定scrollLeft = slider.scrollLeft 就不用在mousemove的時候再找一次
const slider = document.querySelector('.items')
  let isDown = false, startX, scrollLeft

  slider.addEventListener('mousedown', (e) => {
    isDown = true
    slider.classList.add('active')
    startX = e.pageX - slider.offsetLeft
    scrollLeft = slider.scrollLeft
  })
  
  slider.addEventListener('mouseup', () => {
    isDown = false;
    slider.classList.remove('active')
  })
  slider.addEventListener('mouseleave', () => {
    isDown = false;
    slider.classList.remove('active')
  })
  
  slider.addEventListener('mousemove', (e) => {
    if(!isDown) return
    e.preventDefault()
    const x = e.pageX - slider.offsetLeft
    const walk = (x - startX) * 3
    slider.scrollLeft = scrollLeft - walk
  })

上一篇
17—JS挑戰(11)—Sticky Nav + Event Capture, Propagation, Bubbling
下一篇
19–JS挑戰(14)–Video Speed Controller UI +Countdown Clock
系列文
師父領進門 修行在個人30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言