iframe高度自适应

585 阅读1分钟

1、项目是tarojs框架,语法和react一致

2、使用

计算iframe的高度,项目的需求是可以滚动页面,但是由于iframe可能嵌入的是第三方页面,无法获取到第三方页面的高度,所以这里的逻辑就变成了,给iframe设定一个固定高度,使内容在iframe内部滚动,

由于我的项目是在微信公众号使用的,iframe是不支持微信授权登录的,如果iframe内嵌的是本项目内部页面,建议使用组件形式引入

贴下源码

import Taro from "@tarojs/taro";import "./index.scss";/********@param height [require] 类型Number,iframe的高度*************************** *//********@param minusHeight  类型Number,计算iframe时需要减去的额外高度,例如底部固定按钮*************************** */class BaseMyIframe extends Taro.Component {  state = { height: 0 };  downloadTop = 0;  componentDidMount() {    const { minusHeight = 0 } = this.props;    // 获取屏幕高度,计算#app元素的高度,因为当iframe出现时,页面高度固定,不能滚动,#app的高度是屏幕高度减去页面顶部下载app的高度    let query = Taro.createSelectorQuery();    query.select(".index_down_app_tip").boundingClientRect();    query.exec(response => {      if (response[0]) {        this.downloadTop = response[0].top;      }    });    const pageHeight = Taro.getSystemInfoSync().windowHeight;    document.getElementById("app").style.height =      pageHeight - this.downloadTop - minusHeight + "px";    document.getElementById("app").style.overflow = "hidden";  }  //页面销毁时  componentWillUnmount() {    document.getElementById("app").style.height = "auto";    document.getElementById("app").style.overflow = "none";  }  render() {    return (      <iframe        id="external-frame"        style={{          // iframe的width+16px是因为需要隐藏iframe的滚动条          // width: "calc(100% + 16px)",          height: this.props.height + "px"        }}        border="no"        className={"iframe"}        src={this.props.link}        // src={"http://baidu.com"}      ></iframe>    );  }}export default BaseMyIframe;

引入

             <BaseMyIframe                      link={content}                      height={this.iframeHeight}                      minusHeight={58}                    />

计算iframe高度

  // 获取高度  handleGetScrollViewHeight = () => {    let query = Taro.createSelectorQuery();    query.select(".tab").boundingClientRect();    query.select(".tabContener").boundingClientRect();    // wx.getSystemInfoSync()    query.exec(response => {      if (response[0]) {        this.fixTop = response[0].top;      }      let aaa = Taro.getSystemInfoSync().windowHeight;      if (response[1]) {        this.tabContenerfixTop = response[1].top;        this.iframeHeight =          Taro.getSystemInfoSync().windowHeight - response[1].top - 32 - 46;      }    });  };