无法通过 JavaScript 找到实际存在的元素

您好,

我尝试编写一个脚本来获取个人资料标题的 background-image 属性,然后将其保存为根变量。但是,我的代码不起作用。我尝试了许多解决方案,其中一些包括 AI,但它们只是还原了插件版本,并没有提供帮助。

这是代码:

<script type="text/discourse-plugin" version="0.9">
    const setRootBgImage = () => {
        try {
            const el = document.getElementByClassName('.user-profile-image');
            if (el) {
                const bgImage = window.getComputedStyle(el).getPropertyValue('background-image');
                document.documentElement.style.setProperty('--profile-bg-img', bgImage);
            }
        } catch (error) {
            console.error(error);
            debugger; //运行时,无论如何都会出现此问题,并显示相同的错误
        }

    };

    const shouldRun = () => {
        return window.location.pathname.startsWith('/u/');
    };

    const init = () => {
        if (shouldRun()) {
            setRootBgImage();
        }
    };

    document.addEventListener('DOMContentLoaded', init);

    api.onPageChange(() => {
        init();
    });
</script>

谢谢。

2 个赞

您的脚本在页面大部分内容渲染之前加载,因此找不到该元素……

这应该能帮您找到所需内容……

<script type="text/discourse-plugin" version="0.9">
api.onPageChange(() => {
  let currentRouteParent = api.container.lookup("router:main").currentRoute?.parent;
    if (currentRouteParent.name.includes("user")) {
        let userBg = currentRouteParent.attributes.profile_background_upload_url;

        if (userBg) {
            document.documentElement.style.setProperty('--profile-bg-img', userBg);
        } else {
            document.documentElement.style.removeProperty('--profile-bg-img');
      }
    }
});
</script>

我猜您是想在个人资料页面上的某个地方重用用户的个人资料背景?否则,如果您离开个人资料页面并刷新页面,它将不会保留……

2 个赞

那奏效了!不过 CSS 似乎不行。
image

1 个赞

好的,您需要做的是将 url() 部分添加到自定义属性值中…… 就像这样:

document.documentElement.style.setProperty('--profile-bg-img', `url(${userBg})`);
1 个赞

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.