可以通过以下步骤精确计算富文本可视区域:
获取富文本编辑器容器元素和头部工具栏元素。
获取滚动条的当前位置,可视区域高度和容器元素的总高度。
计算容器元素相对于视口的顶部位置。
根据当前滚动条位置和容器元素位置,判断是否需要将头部工具栏吸顶。
如果需要吸顶,则修改头部工具栏的定位方式、位置和宽度。
//监听滚动条滚动富文本吸顶
handleScroll(e) {
this.$nextTick(() => {
let header = document.querySelector(".tox-editor-header");
let container = document.querySelector(".tox-editor-container");
let toolbar = document.querySelector(".tox-toolbar__overflow");
const rectHeader = header.getBoundingClientRect(); //获取容器元素的大小和位置信息
const rect = container.getBoundingClientRect();
const area = rect.height - rectHeader.height;
const scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop ||
0;
const clientTop =
document.documentElement.clientTop || document.body.clientTop || 0;
const top = rect.top + scrollTop - clientTop;
if (header) {
if (top < 0 && Math.abs(top) < area) {
//元素在可视区
header.style.position = "fixed";
header.style.top = "0";
if (container) {
header.style.width = container.clientWidth + "px";
}
} else {
header.style.position = "relative";
header.style = "";
header.style.width = "100%";
container.style.paddingTop = "0";
if (toolbar) {
toolbar.style.display = "none";
}
}
}
});
},
兼容多个富文本编辑器
//监听滚动条滚动富文本吸顶
handleScroll(e) {
this.$nextTick(() => {
let header = document.querySelectorAll(".tox-editor-header");
let container = document.querySelectorAll(".tox-editor-container");
let toolbar = document.querySelectorAll(".tox-toolbar__overflow");
if (header) {
header.forEach((item, index) => {
const rectHeader = item.getBoundingClientRect(); //获取容器元素的大小和位置信息
const rect = container[index].getBoundingClientRect();
const area = rect.height - rectHeader.height;
const scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop ||
0;
const clientTop =
document.documentElement.clientTop ||
document.body.clientTop ||
0;
const top = rect.top + scrollTop - clientTop;
if (top < 0 && Math.abs(top) < area) {
//元素在可视区
item.style.position = "fixed";
item.style.top = "0";
if (container[index]) {
item.style.width = container[index].clientWidth + "px";
}
} else {
item.style.position = "relative";
item.style = "";
item.style.width = "100%";
container[index].style.paddingTop = "0";
if (toolbar[index]) {
toolbar[index].style.display = "none";
}
}
});
}
});
},