色婷婷狠狠18禁久久YY,CHINESE性内射高清国产,国产女人18毛片水真多1,国产AV在线观看

下載時保留樣式.html文件(React)

傅智翔1年前7瀏覽0評論

下面是我的React組件的簡化版本:

export class SomePage extends Component {

  downloadAsHTML() {
    const element = document.createElement("a");

    const file = new Blob([document.getElementById('second-child-div').outerHTML], {
      type: "text/html"
    });

    element.href = URL.createObjectURL(file);
    element.download = "file.html";
    document.body.appendChild(element);
    element.click();
  }

  render () {
    return (
      <>
        <div className="first-child-div">Stuff here</div>
        <div id="second-child-div" onClick={()=>this.downloadAsHTML()}>
           <span className="some-other-styling-here">
              <h1> Title </h1>
              <p> Paragraph </p>
              More things here
           </span>
           More html elements, nested styling, and text here
        </div>
      </>
    )
  }

}

當用戶單擊second-child-div時,div作為。html文件,我想下載。html文件來保留所有類名和html選擇器的樣式(比如#second-child-div h1將在。css)。做這件事的最好方法是什么?

我考慮的一種方法是創建另一個名為Styles.js的文件:

const Styles = {
  container: {
    'padding': '30px',
    'border'
  },
  anotherContainer:  {
    'color': 'blue',
    'background': 'yellow'
  }
  containerH1: {
    'font-size': '20px'
  }
  containerParagraph: {
    'font-size': '20px'
  },
}

export default Styles;

然后像這樣導入它:

import "Styles" from "./Styles.js"

//in second-child-div:

<div id="second-child-div" style={Styles.container} onClick={()=>this.downloadAsHTML()}>
   <span style={Styles.anotherContainer}>
      <h1 style={Styles.containerH1}> Title </h1>
      <p style={Styles.containerParagraph}> Paragraph </p>
       More things here
   </span>
   More html elements, nested styling, and text here
</div>

在我的實際應用中,我有許多樣式,有css選擇器之類的。做這件事最有效的方法是什么?

您可以在單擊按鈕時將CSS加載到頁面中,然后將CSS內聯到& ltstyle & gt標簽,然后保存出來。

這種方法相當暴力。我并不試圖找出哪些樣式適用于您正在導出的元素,它只是獲取所有樣式。

const downloadAsHTML = () => {
  const element = document.createElement("a");

  const domNodeToSave = document.getElementById("second-child-div");
  const modifiedDomNodeToSave = domNodeToSave.cloneNode(true);
  modifiedDomNodeToSave.style.margin =
    "10px"; // example modificaiton

  const htmlSnippet = modifiedDomNodeToSave.outerHTML;

  const styleSheets = document.styleSheets;

  let allStyles = "";

  for (let i = 0; i < styleSheets.length; i++) {
    const styleSheet = styleSheets[i];

    const rules = styleSheet.cssRules;

    for (let j = 0; j < rules.length; j++) {
      const rule = rules[j];

      allStyles += rule.cssText + "\n";
    }
  }

  const styleBlock = `<style>${allStyles}</style>`;
  htmlSnippet += styleBlock;

  const file = new Blob([htmlSnippet], {
    type: "text/html",
  });

  element.href = URL.createObjectURL(file);
  element.download = "file.html";
  document.body.appendChild(element);
  element.click();
};