Dynamically Append Stylesheet to Head Using JavaScript
In certain scenarios, accessing and editing the head section of a web page may be restricted. However, there remains a need to add additional stylesheets to enhance the visual appearance of the site. This raises the question: can we use JavaScript to accomplish this task, ensuring that the stylesheet is inserted after the head tag?
To address this challenge, JavaScript offers a versatile solution:
function addCss(fileName) { var head = document.head; var link = document.createElement("link"); link.type = "text/css"; link.rel = "stylesheet"; link.href = fileName; head.appendChild(link); } addCss('{myUrl}');
Alternatively, if you prefer jQuery:
function addCss(fileName) { var link = $("<link />", { rel: "stylesheet", type: "text/css", href: fileName }); $('head').append(link); } addCss("{myUrl}");
These methods dynamically append the stylesheet link element to the head section of the HTML document, enabling you to add additional styles to your website even if access to the head section is restricted.
위 내용은 JavaScript를 사용하여 헤드에 스타일시트를 동적으로 추가하려면 어떻게 해야 합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!