存在する要素が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.