localStorage.getItem()/setItem()
等皆是預設接受字串,若非字串輸入會自動toString(),所以要先JSON.stringify() 之後要用再JSON.parse()即可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)
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)