問題: placeholder屬性給予了用戶很友好的提示,可是在老版本的瀏覽器中就不會起做用(Internet Explorer 9 及以前的版本不支持 placeholder 屬性),這是一個很頭疼的問題,因而就產生了如下的思考。node
'placeholder' in document.createElement('input')數組
document.querySelectorAll('[placeholder]')瀏覽器
Array.prototype.slice.call(document.querySelectorAll('[placeholder]'))bash
nodes.forEach()ui
var cloneNode = item.cloneNode()this
if (cloneNode.getAttribute('type').toLowerCase() === 'password') { cloneNode.setAttribute('type', 'text') }spa
cloneNode.setAttribute('value', cloneNode.getAttribute('placeholder')) cloneNode.style.display = 'none'prototype
item.insertAdjacentHTML('afterend', cloneNode.outerHTML)code
item.nextSibling.addEventListener('focus', function () { this.style.display = 'none' this.previousSibling.style.display = 'inline' this.previousSibling.focus() })對象
item.addEventListener('focus', function () { this.nextSibling.style.display = 'none' })
item.addEventListener('blur', function () { if (!this.value) { this.style.display = 'none' this.nextSibling.style.display = 'inline' } })
if (!item.value) { item.style.display = 'none' item.nextSibling.style.display = 'inline' }
if (!('placeholder' in document.createElement('input'))) {
// 將返回的nodeList對象轉爲數組
var nodes = Array.prototype.slice.call(document.querySelectorAll('[placeholder]'))
nodes.forEach(function (item, index) {
item.addEventListener('focus', function () {
this.nextSibling.style.display = 'none'
})
item.addEventListener('blur', function () {
if (!this.value) {
this.style.display = 'none'
this.nextSibling.style.display = 'inline'
}
})
var cloneNode = item.cloneNode()
// 若是[type='password']類型,則轉爲text
if (cloneNode.getAttribute('type').toLowerCase() === 'password') {
cloneNode.setAttribute('type', 'text')
}
cloneNode.setAttribute('value', cloneNode.getAttribute('placeholder'))
cloneNode.style.display = 'none'
item.insertAdjacentHTML('afterend', cloneNode.outerHTML)
item.nextSibling.addEventListener('focus', function () {
this.style.display = 'none'
this.previousSibling.style.display = 'inline'
this.previousSibling.focus()
})
if (!item.value) {
item.style.display = 'none'
item.nextSibling.style.display = 'inline'
}
})
}
複製代碼