لا يمكن العثور على عنصر عبر JavaScript موجود بالفعل

مرحباً،

لقد حاولت إنشاء نص برمجي للحصول على السمة background-image من رأس الملف الشخصي، ثم حفظها كمتغير جذر. ومع ذلك، فإن الكود الخاص بي لا يعمل. لقد جربت العديد من الحلول، بعضها تضمن الذكاء الاصطناعي، والذي أعاد فقط إصدار المكون الإضافي ولم يساعد.

هذا هو الكود:

<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.