【问题标题】:Setting iframe height to scrollHeight in GatsbyJS在 GatsbyJS 中将 iframe 高度设置为 scrollHeight
【发布时间】:2019-12-07 20:33:49
【问题描述】:

https://imgur.com/a/AJCoMfN

手机高度不够大。另外,在桌面模式下,即使包含的 div 没有限制,我仍然不明白为什么我的 iframe 有滚动条???为什么不拉伸页面的全部内容?

我的错误是:

TypeError: Cannot read property 'iFrameHeight' of null

我也尝试了这里列出的非反应方式:

https://stackoverflow.com/questions/42042901/setting-iframe-height-to-scrollheight-in-reactjs

但它不起作用

这是我的一些代码:

export default class SecondPage extends Component {
  componentDidMount() {
    const obj = ReactDOM.findDOMNode(this);
    this.setState({ iFrameHeight: obj.contentWindow.document.body.scrollHeight + 'px' });
  }


  render() {
    return (
      <Layout>
        <div className="iframe-container">
          <iframe
            src="https://www.1.com/1.php"
            height={this.state.iFrameHeight}
            style={{ "maxWidth": "100%", "border": "none", "overflow": "auto" }}>
            <p>
              <a href="https://www.1.com/1.php" title="Book Now">Button go</a>
            </p>
          </iframe>
        </div>
      </Layout>
    );
  }
}

我的 CSS:

.iframe-container {
  overflow: hidden;
  padding-top: 56.25%;
  position: relative;
}

.iframe-container iframe {
   border: 0;
   height: 100%;
   left: 0;
   position: absolute;
   top: 0;
   width: 100%;
}

【问题讨论】:

    标签: javascript css reactjs iframe gatsby


    【解决方案1】:

    您遇到的错误是由于未初始化 state。你需要在你的组件中添加这样的东西:

    constructor(props) {
      super(props)
      this.state = { iFrameHeight: 0 }
    }
    

    关于 iframe 大小的第二个问题:iframe 不会根据其内容动态增长/收缩。有一些方法可以使用postMessage API 与嵌入式 iframe 进行通信,但嵌入式站点需要测量其内容的宽度并将其提供给父/嵌入站点以供应用程序使用。

    【讨论】:

    • @Link 这回答了你的问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-29
    • 2012-10-24
    • 2014-05-26
    • 2019-11-18
    • 1970-01-01
    • 2013-02-21
    • 2018-06-30
    相关资源
    最近更新 更多