Creating a
-
Create a : First, use the
document.createElementmethod to create a new -
Set the style content: Then, utilize the
textContentproperty or theappendChildmethod combined withcreateTextNodeto define CSS rules. -
Insert the : Finally, employ the
document.head.appendChildmethod to add the newly created
Here is a specific implementation:
javascript// Create a new style element var style = document.createElement('style'); // Set CSS rules // Example: Apply background color and font color to the body style.textContent = `\n body {\n background-color: #f3f3f3;\n color: #333;\n }\n`; // Insert the style element into the head document.head.appendChild(style);
In this example, I configured the page background color and font color. Naturally, you can incorporate any CSS rules as required. This technique enables dynamic control over page styles and can be leveraged to adjust styles based on user interactions or other events.
2024年6月29日 12:07 回复