iT邦幫忙

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

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

JS挑戰-(8)- LocalStorage + Mouse move CSS

  • 分享至 

  • xImage
  •  
  1. 15- LocalStorage !!! and event delegation
  • e.preventDefault()
  • 抽象化 讓函數可以更通用
  • [object object] 因為localStorage.getItem()/setItem()等皆是預設接受字串,若非字串輸入會自動toString(),所以要先JSON.stringify() 之後要用再JSON.parse()即可
  • 函數與監聽的順序,若要監聽的東西在之後才產生會監聽不到,所以要用固定的東西來聽會變的東西
  • 延伸:checkAll, uncheckAll, delete
const addItems = document.querySelector('.add-items')
  const itemsList = document.querySelector('.plates')
  const items = JSON.parse(localStorage.getItem('items')) || []  //重點!!!

  function addItem(e) {
    e.preventDefault()
    const text = (this.querySelector('[name=item]')).value
    const item = {
      text,
      done: false
    }
    items.push(item)
    populateList(items, itemsList)
    localStorage.setItem('items', JSON.stringify(items))
    this.reset()
  }

  function populateList(alists = [], acollection) {
    acollection.innerHTML = alists.map((alist, i) => {
      return`
        <li>
          <input type="checkbox" data-index=${i} id= "item${i}" ${alist.done? 'checked' : "" } />
          <label for="item${i}">${alist.text}</label>
        </li>
      `
    }).join('')
  }
  function toggleDone(e) {
    if (!e.target.matches('input')) return
    const el = e.target
    const index = el.dataset.index
    items[index].done = !items[index].done
    localStorage.setItem('items', JSON.stringify(items))
    populateList(items, itemsList)
  }

  addItems.addEventListener('submit', addItem)
  itemsList.addEventListener('click', toggleDone)
  populateList(items, itemsList)
  1. 16- CSS text shadow mouse move event
  • normalize: 用e.target找問題在哪!
  const hero = document.querySelector('.hero')
  const text = hero.querySelector('h1')
  const walk = 100


  function shadow(e) {
    const {offsetWidth: width, offsetHeight: height} = hero
    let {offsetX : x, offsetY: y} = e
    if(this !== e.target){  //normalize
      x = x + e.target.offsetLeft ;
      y = y + e.target.offsetTop  ;
    }

    const xWalk = Math.round((x /width * walk)- (walk/2))
    const yWalk = Math.round((y /height * walk)- (walk/2))
    //console.log(xWalk, yWalk);  // -50,50 ~ 50,50

    text.style.textShadow = `${xWalk}px ${yWalk}px 0 #ddd `
  }


  hero.addEventListener('mousemove', shadow)

上一篇
JS挑戰—(7)— Slide in on Scroll+Reference and Copy
下一篇
JS挑戰–(9)- map + reduce!
系列文
師父領進門 修行在個人30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言