placeholder属性定义: placeholder 属性规定可描述输入字段预期值的简短的提示信息(好比:一个样本值或者预期格式的短描述)。html
问题来源: placeholder属性给予了用户很友好的提示,可是在老版本的浏览器中就不会起做用(Internet Explorer 9 及以前的版本不支持 placeholder 属性),这是一个很头疼的问题,因而就产生了如下的思考。node
'placeholder' in document.createElement('input')
document.querySelectorAll('[placeholder]')
Array.prototype.slice.call(document.querySelectorAll('[placeholder]'))
nodes.forEach()
var cloneNode = item.cloneNode()
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() })
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' } }) }
因为本人学识有限,有不少须要提高的地方,望你们多多指教。数组