萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實作 iframe 拖曳調整寬高 (三版本演進)

版本一:基本拖曳 (透明 div 做把手)

<iframe id="a" src="tree.htm" style="width:200px;height:610px;position:absolute;z-index:9"></iframe>
<div id="ab" style="width:5px;height:799px;background:#aaffaa;position:absolute;left:200px;z-index:100;filter:alpha(opacity=0);cursor:e-resize"
     onmousedown="down()" onmousemove="move()" onmouseup="up()"></div>
<iframe id="b" src="index.htm" style="width:799px;height:612px;position:absolute;left:205px;z-index:10"></iframe>

<script>
var mouseX=0, mouseY=0, w=5;
function down(){ mouseX=event.x; mouseY=event.y; }
function move(){
  var a=document.getElementById('a'), b=document.getElementById('b'), ab=document.getElementById('ab');
  if(event.button==1){
    a.style.width=parseInt(a.offsetWidth)+(event.x-mouseX)+'px';
    a.style.height=parseInt(a.offsetHeight)+(event.y-mouseY)+'px';
    mouseX=event.x; mouseY=event.y;
    ab.style.left=a.offsetWidth-ab.offsetWidth/2+'px';
    ab.style.height=a.clientHeight+'px';
    b.style.height=a.clientHeight+'px';
    b.style.left=a.clientWidth+w+'px';
    b.style.width=screen.width-a.offsetWidth-w+'px';
  }
}
function up(){
  document.getElementById('ab').style.left=document.getElementById('a').offsetWidth+'px';
  mouseX=mouseY=0;
}
</script>

版本二:表格布局 + setCapture (效能較佳)

<table style="width:100%;height:100%" border=0 cellspacing=0 cellpadding=0>
<tr>
  <td style="width:150px"><iframe id="a" src="tree.htm" style="width:100%;height:100%"></iframe></td>
  <td style="width:2px;cursor:e-resize;background:#ccc"
      onmousedown="Resize_mousedown(event,this)" onmousemove="Resize_mousemove(event,this)" onmouseup="Resize_mouseup(event,this)"></td>
  <td><iframe id="b" src="index.htm" style="width:100%;height:100%"></iframe></td>
</tr></table>

<script>
var isResizing=false;
function Resize_mousedown(e,td){ td.mouseDownX=e.clientX; td.leftTdW=td.previousSibling.offsetWidth; td.setCapture(); isResizing=true; }
function Resize_mousemove(e,td){ if(!isResizing)return; var nw=td.leftTdW+e.clientX-td.mouseDownX; td.previousSibling.style.width=(nw>0?nw:1)+'px'; }
function Resize_mouseup(e,td){ if(!isResizing)return; td.releaseCapture(); isResizing=false; }
</script>

版本三:加入預設寬度切換按鈕

<td ...><font style="cursor:pointer" onmousedown="Resize_setDefault(event,this)"><</font></td>
function Resize_setDefault(e,font){
  var td=font.parentNode, left=td.previousSibling;
  if(font.innerText=='<'){ left.style.width='1px'; font.innerText='>'; }
  else{ left.style.width='150px'; font.innerText='<'; }
  e.cancelBubble=true;
}

關鍵技巧總結

  • filter:alpha(opacity=0) 讓把手透明但可接收滑鼠事件
  • setCapture/releaseCapture 解決滑鼠移出把手仍能拖曳
  • 表格布局天然自適應高度,比 absolute 定位更穩定
copyright © 萬盛學電腦網 all rights reserved