无法访问DOM元素style属性,无法修改文本元素样式
text.style in Your Loading Animation Let’s break down why you might be having issues accessing the style property of your text element, and fix it step by step:
First: Confirm the Element is Being Selected
If text.style is throwing an error (like Cannot read properties of null), that means your document.querySelector('.loading-text') isn’t finding the element. To verify this, add a quick check:
const text = document.querySelector('.loading-text'); if (!text) { console.error('Whoops! No element with class "loading-text" found.'); }
If this logs an error, fix these common issues:
- Make sure your script runs after the DOM is loaded (put it at the end of your
<body>tag, or wrap it in aDOMContentLoadedevent listener). - Double-check the class name spelling—class names are case-sensitive!
Second: Use text.style Correctly
If the element is found but you’re unsure how to modify styles, you need to target specific CSS properties via the style object. For example, if you want to fade the text out as the count increases, here’s how to update your blurr function:
function blurr() { if (count > 99) { clearInterval(interval); } text.innerHTML = `${count}%`; // Example: Adjust opacity based on the count const opacityValue = 1 - (count / 100); text.style.opacity = opacityValue; // Another example: Shrink the font size text.style.fontSize = `${100 - count}px`; count++; }
You can modify any inline style this way—just use camelCase for CSS properties (e.g., backgroundColor instead of background-color).
Full Working Example
To ensure everything runs smoothly, wrap your code in a DOMContentLoaded listener to wait for the page to load:
document.addEventListener('DOMContentLoaded', () => { const bg = document.querySelector(".bg"); const text = document.querySelector('.loading-text'); if (!text) { console.error('Loading text element not found!'); return; } let count = 0; const interval = setInterval(blurr, 30); function blurr() { if (count > 99) { clearInterval(interval); } text.innerHTML = `${count}%`; // Adjust opacity and blur as the count increases text.style.opacity = 1 - count / 100; text.style.filter = `blur(${count}px)`; count++; } });
Content of the question来源于stack exchange,提问作者benefiting_The_believer

