如何在 iFrame 中使用 tailwind?

6

如何在开发中使用tailwind和iFrame?

目前,当我添加新的样式时,我会创建一个新的CSS文件:

npx tailwindcss build src/assets/css/tailwind.css -o dist/assets/css/index.css

在开发过程中,我想将该文件链接到我的iFrame中,但这有点麻烦...有更好的方法吗?

你解决了这个问题吗? - quantdaddy
抱歉,对于我的设计系统仍需按照那种方式进行。;( - Gregor Voinov
你找到任何答案了吗? - Arjunsingh thakur
1个回答

0
你可以将tailwind cdn注入到iframe中。
工作演示:https://codesandbox.io/s/elastic-pascal-3y46c5 自动注入tailwind演示:https://codesandbox.io/s/silly-goldwasser-5o50bx?file=/index.html 演示代码: index.html:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>
  <script>
    function etw() {
      var iframe = document.getElementById("iframe");
      var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
      var tw = iframeDoc.createElement("script");
      tw.setAttribute("src", "https://cdn.tailwindcss.com");
      tw.onload = function () {
        iframeDoc.body.innerHTML = iframeDoc.body.innerHTML; //re-render
      };
      iframeDoc.head.appendChild(tw);
    }
  </script>
  <body>
    <iframe id="iframe" src="/hello.html" title="IFrame"></iframe>
    <button onclick="etw()">click to enable tailwind in the iframe</button>
  </body>
</html>

hello.html:

<div class="bg-red-500 text-xl p-5 rounded-full">
  class="bg-red-500 text-xl p-5 rounded-full" div
</div>

第二个示例 index.html(自动注入):

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>
  <script>
    function etw() {
      var iframe = document.getElementById("iframe");
      var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
      var tw = iframeDoc.createElement("script");
      tw.setAttribute("src", "https://cdn.tailwindcss.com");
      tw.onload = function () {
        iframeDoc.body.innerHTML = iframeDoc.body.innerHTML; //re render
      };
      iframeDoc.head.appendChild(tw);
    }
    window.addEventListener("DOMContentLoaded", function () {
      iframe.contentWindow.addEventListener("DOMContentLoaded", etw);
    });
  </script>
  <body>
    <iframe id="iframe" src="/hello.html" title="IFrame"></iframe>
  </body>
</html>

注意:

使用Play CDN可以在浏览器中尝试Tailwind,无需任何构建步骤。Play CDN仅用于开发目的,不是生产环境的最佳选择。


这可能是一个愚蠢的问题,但我无法让它起作用。如果不是点击按钮,而是在加载时,Tailwind 样式应该如何在 iframe 中起作用?显然,可以使用包含指向 Tailwind CDN 的 src 的 script 标记,但是我尝试将其加载时无法正常工作...你能否提供另一个 CodeSandbox? - wongz
谢谢,很有帮助!对于未来的任何其他人,我还意识到当直接将cdn放在头部时,我的代码不起作用,因为我写成了“className”而不是“class”……噫! - wongz
很有可能Tailwind的颜色标记与客户端的颜色不匹配...所以这不是一个真正的解决方案。 - Gregor Voinov
@GregorVoinov https://tailwindcss.com/docs/installation/play-cdn 查看第2部分,“尝试自定义配置”。 - ATP
无论如何,请注意 CDN 非常慢。 - ATP
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接