新来的产品经理,想作一个和qq或者微信聊天同样的,上下拖动动态改变文本内容框和编辑器布局的需求。 其实一开始是一头雾水的,可是经过万能的mdn,以及充满智慧的我,最终仍是完成了这个需求。 其中最核心的仍是ResizeObserver这个第一次用的类,因此会在这里作一些记录。css
entries是一个数组,它由全部的ResizeObserverEntry object组成。经过for (let entry of entries) {}的方式
,entry表明一个ResizeObserver object,一个entry由contentRect和target组成。html
在resize相关实践中,entry的contentRect对象是最最重要的。前端
{target: div, contentRect: DOMRectReadOnly}
contentRect: DOMRectReadOnly
bottom: 312.3125
height: 292.3125
left: 20
right: 626
top: 20
width: 606
x: 20
y: 20
__proto__: DOMRectReadOnly
target: div
__proto__: ResizeObserverEntry
复制代码
<div class="main" :style="{minHeight: dynamicMainHeight}">
<chatView></chatView>
</div>
复制代码
.main {
resize: vertical;
overflow: auto;
}
复制代码
observeChatView() {
if (window.ResizeObserver) {
const viewElem = document.querySelector('.main');
const resizeObserver = new ResizeObserver((entries) => {
for (const entry of entries) {
if (!this.initialHeight) {
this.initialHeight = entry.contentRect.height;
}
if (this.initialHeight) {
const deltaHeight = this.initialHeight - entry.contentRect.height;
this.$bus.$emit('rerenderViewAndEditor', deltaHeight);
}
}
});
resizeObserver.observe(viewElem);
} else {
this.$Message.warning('不支持ResizeObserver');
}
},
},
复制代码
<div class="rich-text-editor" contenteditable data-placeholder="按下Enter发送消息,按下Shift+Enter换行" :style="{height: dynamicHeight}" ></div>
复制代码
computed: {
dynamicHeight() {
return `${defaultEditorHeight + this.deltaHeight}px`;
},
},
this.$bus.$on('rerenderViewAndEditor', (deltaHeight) => {
this.deltaHeight = deltaHeight;
});
复制代码
自动跳到最新一条消息的chatView组件须要减去deltaHeight,从而增大scrollHeight的高度。git
this.$bus.$on('rerenderViewAndEditor', (deltaHeight) => {
this.visiableHeight = document.body.clientHeight - deltaHeight;
this.deltaHeight = deltaHeight;
});
scrollToBottom() {
this.$nextTick(() => {
this.scrollTop = this.scrollHeight - this.deltaHeight;
});
},
复制代码
developer.mozilla.org/en-US/docs/… github.com/mdn/dom-exa…github
努力成为优秀的前端工程师!数组