js实现左右拖动,改变导航栏的宽度

本文介绍了一种简单的实现方法,通过拖动条来调整网页导航栏的宽度,适用于左侧导航栏树形菜单等级较多或标题较长的情况。文中提供了一个具体的HTML和JavaScript实例,演示如何使用鼠标操作调整导航栏的显示区域。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近接了一个需求,由于左侧导航栏树形菜单等级比较多或标题比较长,导致显示不完全,需要把导航栏改为可拖动改变显示区域大小。在网上找了一个比较简单易理解的做法,记下来供大家参考。

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>demo</title>
<style>
ul,li{margin:0;padding:0;}
body{font:14px/1.5 Arial;color:#666;}
#box{position:relative;width:600px;height:400px;border:2px solid #000;margin:10px auto;overflow:hidden;}
#box ul{list-style-position:inside;margin:10px;}
#top,#bottom{color:#FFF;width:300px;height:400px;overflow:hidden;}
#top{background:green; float:left}
#bottom{background:skyblue;float:right}
#line{position:absolute;top:0;left:50%;height:100%;width:4px;overflow:hidden;background:red;cursor:w-resize;}
</style>
</head>
<body>
<center>左右拖动红条可改变显示区域宽度<span id="msg"></span></center>
<div id="box">
 <div id="top">
 左
 </div>
 <div id="bottom">
 右
 </div>
 <div id="line"></div>
</div>

<script>
function $(id) {
 return document.getElementById(id); 
}
window.onload = function() {
 var oBox = $("box"), oTop = $("top"), oBottom = $("bottom"), oLine = $("line");

 oLine.onmousedown = function(e) {
  console.log(e);
   var disX = (e || event).clientX;
   oLine.left = oLine.offsetLeft;

   document.onmousemove = function(e) { 
      var iT = oLine.left + ((e || event).clientX - disX);
      var e=e||window.event,tarnameb=e.target||e.srcElement;
      var maxT = oBox.clientWidth - oLine.clientWidth;
      oLine.style.margin = 0;
      iT < 0 && (iT = 0);
      iT > maxT && (iT = maxT);
      oLine.style.left = oTop.style.width = iT + "px";
      oBottom.style.width = oBox.clientWidth - iT + "px";
     $("msg").innerText='top.width:'+oLine.style.width+'---bottom.width:'+oBottom.style.width+'---oLine.offsetLeft:'+oLine.offsetLeft+'---disX:'+disX+'---tarnameb:'+tarnameb.tagName;
      return false
   }; 

   document.onmouseup = function() {
    document.onmousemove = null;
    document.onmouseup = null; 
    oLine.releaseCapture && oLine.releaseCapture()
   };
   oLine.setCapture && oLine.setCapture();
  return false
 };
};
</script>
</body>
</html>

若想变为自适应的,可以把宽高设置为百分比。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值