3 回答

TA貢獻1799條經驗 獲得超6個贊
我認為最好的選擇是將 HTML 頁面加載到 iframe 中,從 iframe 中查詢樣式,然后將其附加到當前文檔。
除了<style>
塊之外,不會從 HTML 中復制任何內容。不過,外部 HTML 文檔必須是實際的 HTML 文檔 (?<html><head><style>....
),否則將無法查詢頁面以檢索 CSS。
這是純 JavaScript 中的示例:
// Create an iframe
const iframe = document.createElement("iframe");
// Make it not visible
iframe.style.visibility = "hidden";
// This will run once the HTML page has loaded in the <iframe>
iframe.onload = () => {
? // Find the <style> element in the HTML document
? const style = iframe.contentDocument.querySelector("style");
? // Take that <style> element and append it to the current document's <head>
? document.querySelector("head").appendChild(style);
? // Remove the <iframe> after we are done.
? iframe.parentElement.removeChild(iframe);
};
// Setting a source starts the loading process
iframe.src = "css.html";
// The <iframe> doesn't actually load until it is appended to a document
document.querySelector("body").appendChild(iframe);

TA貢獻1966條經驗 獲得超4個贊
它可以以不同的方式實現(xiàn)。然而不是通過JS,而是PHP include
然而,為此,您的服務器需要支持 PHP,并且需要使用 PHP 而不是 HTML 作為文檔。現(xiàn)在聽起來比實際情況更復雜。要使用 PHP,必須.php在末尾調用該文檔,而不是.html例如index.php。文檔本身的編寫方式與編寫 HTML 網站的方式完全相同。
現(xiàn)在使用 PHP include 來解決這個問題。你將 CSS 包含為頭部樣式:
索引.php:
<html>
<head>
<?php
include('styles.css');
?>
</head>
<body>
content
</body>
</html>
該行<?php include('url'); ?>
會將 url 服務器端提到的文件加載到文檔中。因此,您只需要創(chuàng)建另一個具有該名稱的文件styles.css
,并以正常方式在其中寫入 css 即可。
添加回答
舉報