首页 > 解决方案 > 如何将 html 和 js 代码包含到一个 js 文件中?

问题描述

我需要包含一个 iframe,它必须是响应式的,在多个网站中没有滚动。我需要用这样的一行代码来做到这一点:

<script src="testfile.js"></script>

这是我必须以某种方式包含在 testfile.js 中的 html 代码

<!doctype html>
<html class="no-js" lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Seamless.js | Beautiful, seamless iframes.</title>
  <script src="../build/seamless.parent.js"></script>
  <script type="text/javascript">
    window.onload = function() {
      window.seamless(document.getElementById('childpage'), {
        fallbackText: 'Having Trouble?'
      });
    };
  </script>
</head>
<body>
<div class="row panel">
  <div class="large-12 columns">
    <iframe id="childpage" src="example1.child.html?id=###"></iframe>
  </div>
</div>
</body>
</html>

我只能使用 iframe 部分来获得一行代码:

 <iframe id="childpage" src="example1.child.html?id=###"></iframe>

但我需要额外的 html 和 js,以使 iframe 响应并具有可调节的宽度

标签: javascripthtml

解决方案


您不能在 js 中显式使用 HTML 代码,要编辑 html 标签的属性,您可以执行以下操作。只需使用 getElementsByTagName("iframe").style 来获取 HTML 页面中 iframe 的所有 CSS 引用,然后您可以相应地设置它们。

<!doctype html>
<html class="no-js" lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Seamless.js | Beautiful, seamless iframes.</title>
  <script src="../build/seamless.parent.js"></script>
   <script type="text/javascript">
    window.onload = function() {
      window.seamless(document.getElementById('childpage'), {
        fallbackText: 'Having Trouble?'
      });
    };
  </script>
  <script src="testfile.js"></script>
</head>
<body onload="myFunction()">
<div class="row panel">
  <div class="large-12 columns">
    <iframe id="childpage" src="example1.child.html?id=###"></iframe>
  </div>
</div>
</body>
</html>

测试文件.js

function myFunction() {
  document.getElementsByTagName("iframe").style.overflow="hidden";
}

如果有效,请在线程中响应。


推荐阅读