// 监听textarea
let observe
if (window.attachEvent) {
observe = function (element, event, handler) {
if (element) {
element.attachEvent('on' + event, handler)
}
}
} else {
observe = function (element, event, handler) {
if (element) {
element.addEventListener(event, handler, false)
}
}
}
... // 省略代码
mounted () {
this.initWatchTextarea()
},
data () {
return {
handleAreaHeight: false
}
}
... // 省略代码
initWatchTextarea () {
// 监听textarea
let self = this
let text = document.getElementById('address') // textarea
function resize () {
text.style.height = '.4rem'
if (self.handleAreaHeight) {
text.style.height = text.scrollHeight + 'px'
} else {
setTimeout(() => {
text.style.height = text.scrollHeight + 'px'
self.handleAreaHeight = true
}, 500)
}
}
/* 0-timeout to get the already changed text */
function delayedResize () {
window.setTimeout(resize, 0)
}
observe(text, 'change', delayedResize)
observe(text, 'cut', delayedResize)
observe(text, 'paste', delayedResize)
observe(text, 'drop', delayedResize)
observe(text, 'keydown', delayedResize)
// text.focus()
// text.select()
resize()
}
另外监听移动端input textarea事件
input.addEventListener('input', () => {
// 可搭配上面的resize方法食用 可监听到联想输入之类的
})