最近是有在看Element UI源码的,无意间查阅文档的时候看到
input组件中的自适应文本高度的文本域,这个平常没怎么用到过,在文档上去试了一下后原来是这样的功能,感觉这个还挺实用的,可以用在发表评论的功能中。于是先在脑海里想了一下自己会怎么去写,哈哈,想了一会还是不知道怎么去写,作为菜鸟的我只好打开源码进行一番学习
Element UI是怎么写的
我觉得大概就是分为这四个步骤,下面我们来细品
calculateNodeStyling
Element UI中实现自适应高度的textarea,需要传递一个autosize对象,有minRows最小行数和maxRows最大行数。现在根据第一步来看
const CONTEXT_STYLE = [
'letter-spacing',
'line-height',
'padding-top',
'padding-bottom',
'font-family',
'font-weight',
'font-size',
'text-rendering',
'text-transform',
'width',
'text-indent',
'padding-left',
'padding-right',
'border-width',
'box-sizing'
];
function calculateNodeStyling(targetElement) {
const style = window.getComputedStyle(targetElement)
const boxSizing = style.getPropertyValue('box-sizing')
const paddingSize = (
parseFloat(style.getPropertyValue('padding-bottom')) +
parseFloat(style.getPropertyValue('padding-top'))
)
const borderSize = (
parseFloat(style.getPropertyValue('border-bottom-width')) +
parseFloat(style.getPropertyValue('border-top-width'))
)
const contextStyle = CONTEXT_STYLE
.map(name => `${name}:${style.getPropertyValue(name)}`)
.join(';')
return { contextStyle, paddingSize, borderSize, boxSizing }
}
这一段获取目标元素样式值得代码,我的理解是像box-sizing,padding,border以及CONTEXT_STYLE中定义的都是对一个高度计算会产生影响的属性,因此会在创建新元素之前获取目标元素样式值
创建一个相同的目标元素
let hiddenTextarea
if (!hiddenTextarea) {
hiddenTextarea = document.createElement('textarea');
document.body.appendChild(hiddenTextarea);
}
为新创建元素赋值样式
let {
paddingSize,
borderSize,
boxSizing,
contextStyle
} = calculateNodeStyling(targetElement);
hiddenTextarea.setAttribute('style', `${contextStyle};${HIDDEN_STYLE}`);
const HIDDEN_STYLE = `
height:0 !important;
visibility:hidden !important;
overflow:hidden !important;
position:absolute !important;
z-index:-1000 !important;
top:0 !important;
right:0 !important
`;
其中设置HIDDEN_STYLE样式的目的是将元素隐藏起来
高度计算
这里就是自适应高度的核心代码了
hiddenTextarea.value = targetElement.value || targetElement.placeholder || ''
let height = hiddenTextarea.scrollHeight
const result = {}
if (boxSizing === 'border-box') {
height = height + borderSize
} else if (boxSizing === 'content-box') {
height = height - paddingSize
}
hiddenTextarea.value = '';
let singleRowHeight = hiddenTextarea.scrollHeight - paddingSize;
if (minRows !== null) {
let minHeight = singleRowHeight * minRows;
if (boxSizing === 'border-box') {
minHeight = minHeight + paddingSize + borderSize;
}
height = Math.max(minHeight, height);
result.minHeight = `${ minHeight }px`;
}
if (maxRows !== null) {
let maxHeight = singleRowHeight * maxRows;
if (boxSizing === 'border-box') {
maxHeight = maxHeight + paddingSize + borderSize;
}
height = Math.min(maxHeight, height);
}
result.height = `${ height }px`;
hiddenTextarea.parentNode && hiddenTextarea.parentNode.removeChild(hiddenTextarea);
hiddenTextarea = null;
return result;
将textarea的值赋值给hiddenTextarea取得元素内容的高度,关于scrollHeight可以查看MDN文档,需要注意的是这个高度计算的值是将padding计算在内的。
接着将hiddenTextarea的value值清空,根据传过来的minRows和maxRows计算一个最小高度和最大高度。
看完后自己也写一个
看完代码后是不是就有点冲动想看看自己是不是也会了,根据Element UI最后自己也是实现了下