首页 > 解决方案 > 支持在 JavaScript 中调整两个并排 iframe 的大小

问题描述

我有一个网页,我需要并排显示两个 iFrame,并允许用户水平调整它们的大小(这样他们就可以轻松地看到任一侧的完整内容)。

我的代码如下所示:

<div style="padding:30px">
  <table style="width:100%;border:0px;border-collapse:collapse;">
    <tr>
      <td class="cLeft cSide">
        <iframe class="cFrame" src="{MyLeftPage}">
        </iframe>
      </td>
      <td class="cRight cSide">
        <iframe class="cFrame" src="{MyRightPage}">
        </iframe>
      </td>
    </tr>
  </table>
</div>

标签: javascripthtmljquery

解决方案


最后管理它:jsFiddle

使用此处提到的标准方法的问题(感谢用户!)是当您拥有 iFrame 并将鼠标移到它们上方时,$(document).mousemove()停止触发。

诀窍是在中间有一列,并在单击该列时显示一个 div。由于 div 位于父页面中,因此mousemove事件会不断触发,让您可以轻松调整它的大小。

最终的 HTML 如下所示:

<div style="user-select:none;padding:30px">
  <table style="width:100%;border:0px;border-collapse:collapse;">
    <tr>
      <td class="cLeft cSide">
        <iframe class="cFrame" src="{MyLeftPage}">
        </iframe>
      </td>
      <td class="resize-bar">
        <div class="resize-panel"></div>
      </td>
      <td class="cRight cSide">
        <iframe class="cFrame" src="{MyRightPage}">
        </iframe>
      </td>
    </tr>
  </table>
</div>

这是CSS

.resize-bar {
  width: 5px;
  cursor: col-resize;
  position:relative;
  background-color: #AAA;
  margin:20px;
}
.resize-panel {
  height: 100%;
  background-color: #DDDDDD00;
  display: inline-block;
  position: absolute;
  top:0px;
  left:-2px;
  right:-2px;
  cursor: col-resize;
}
.resize-panel.rx {
    left:-400px;
    right:-400px;
}

.cSide {
    min-width:200px;
}

.cFrame {
  width: 100%;
  border: 1px solid #DDD;
  height: calc(100vh - 170px);
  overflow-x:scroll;
}

这是 JavaScript:

$(function() {
  var pressed = false;

  $("table td").mousedown(function(e) {
    pressed = true;
    $(".resize-panel").addClass("rx");
    e.stopPropagation();
  });

  $(".resize-panel").mousedown(function(e) {
    pressed = false;
  });

  $(document).mousemove(function(e) {
    if (e.which == 1 && pressed) {
      var ww = $(window).width();
      var cPos = e.pageX;

      if (cPos < 0.20 * ww) cPos = 0.2 * ww;
      if (cPos > 0.80 * ww) cPos = 0.8 * ww; {
        $(".cLeft").width(cPos);
      }
    }
  });

  $(document).mouseup(function() {
    if (pressed) {
      $(".resize-panel").removeClass("rx");
      pressed = false;
    }
  });
});


推荐阅读