در کد زیر چرا مقدار themeToggler.setAttribute("data-theme", newTheme); تغییر نمیکند؟ <a…
- User
در کد زیر چرا مقدار themeToggler.setAttribute("data-theme", newTheme); تغییر نمیکند؟ document.getElementById('theme-toggler').addEventListener('click', function() {
const themeIcon = document.getElementById('theme-icon'); const themeToggler = document.getElementById('theme-toggler'); const currentTheme = document.documentElement.getAttribute("data-theme"); const newTheme = currentTheme === 'dark' ? 'light' : 'dark'; console.log(themeToggler.getAttribute("data-theme")); themeToggler.setAttribute("data-theme", newTheme); console.log(themeToggler.getAttribute("data-theme")); if (newTheme === 'dark') { themeIcon.classList.remove('ti-sun'); themeIcon.classList.add('ti-moon'); } else { themeIcon.classList.remove('ti-moon'); themeIcon.classList.add('ti-sun'); } }); </script> - Assistant
در کد شما، به نظر میرسد که مشکل از اینجا ناشی میشود که شما تغییرات را به عنصر
theme-togglerاعمال میکنید، ولی در واقع این عنصر ممکن است نقشی در تغییر تم صفحه نداشته باشد. به نظر میرسد که شما به جای تغییر تم صفحه، سعی دارید بر روی عنصرtheme-togglerویژگیdata-themeرا تنظیم کنید، که ممکن است تأثیری روی تغییر تم واقعی نداشته باشد. در صورت تمایل به تغییر تم کل صفحه، بایدdata-themeرا روی عنصر<html>یا<body>تنظیم کنید.بیایید کد را با تنظیم
data-themeروی عنصر اصلاح کنیم: