页面加载之间的getBoundingClientRect偏差,可以选择吗?

时间:2018-12-28 15:56:55

标签: javascript web

我正在尝试制作一个动画类别导航面板,我希望突出显示的背景移至所选类别:https://gyazo.com/78119b65275f1905bdb8f5ff03ea4746

为此,我动态地使用getBoundingClientRect来获取应该放置块的正确位置。尽管在页面加载之间,但有时有时会无缘无故地偏移这些值,并且看起来像这样:https://gyazo.com/798be154e3817261bd8f0aa3ec40ac2d

我的代码非常简单,我不知道是否有解决此问题的方法,或者是否必须找到避免getBoundingClientRect的其他方法。

const projectCategories = document.getElementById("project-categories");
const selector = document.getElementById("category-selector");
const offset = projectCategories.getBoundingClientRect();
const offsetX = offset.left;
console.log(offsetX);
const offsetY = offset.top;
function moveSelector(selector, left, width, height, offsetX, offsetY) {
    selector.style.width = width + "px";
    selector.style.height = height + "px";
    selector.style.transform = "translateX(" + (left - offsetX) + "px)";
}
const initialCategory = document.getElementById("project-categories").getElementsByClassName("active")[0];
const meta = initialCategory.getBoundingClientRect();
const top = meta.top;
moveSelector(selector, meta.left, meta.width, meta.height, offsetX, offsetY);
selector.style.top = (top - offsetY) + "px";
projectCategories.addEventListener("click", (e) => {
    const target = e.target;
    if (target.nodeName === "A") {
        const meta = target.getBoundingClientRect();
        const height = meta.height;
        const width = meta.width;
        const left = meta.left;
        projectCategories.getElementsByClassName("active")[0].classList.remove("active");
        target.classList.add("active");
        moveSelector(selector, left, width, height, offsetX, offsetY);
    }
});

0 个答案:

没有答案