div内元素是否在可见区域的判断与控制

应用场景:当DIV内的元素较多时,垂直滚动条很长,我们希望在div外的某项操作能让div内相关的元素自动定位,而不必去手动拖动滚动条,反复寻寻觅觅。

这里,我们只考虑垂直滚动条的情况,使用到div的几个属性即可,分别是:

  • scrollTop
  • scrollHeight
  • clientHeight
而要定位的元素,只需要使用到 offsetTop 属性即可。

基本原理:可见区域总是为 scrollTop 至 scrollTop + clientHeight的区域,只要元素的 offsetTop 在这个范围,即为可见。简单吧,意思就是说,滚动条当然代表的位置为可见的起点,可见的范围当然就是本身所具备的高度。由此,置元素可见,则只需要设置 scrollTop 到元素的 offsetTop 位置即可,严格的来说,是到元素 offsetTop 与 offsetTop - clientHeight 之间即可。

直接看实例,您可以复制代码存为html文件在浏览器中查看。
<html>
<head>
<style type="text/css">
button {margin:5px;}
#see { background-color: green; color:yellow;}
</style>
</head>
<body style="font-size:12px; line-height:25px;">
<div id="divScroll" style="width:300px;height:200px;overflow-y:scroll;border:1px solid gray;">
	<button id="b01">点击我哦</button><br />
	<button id="b02">点击我哦</button><br />
	<button id="b03">点击我哦</button><br />
	<button id="b04">点击我哦</button><br />
	<button id="b05">点击我哦</button><br />
	<button id="b06">点击我哦</button><br />
	<button id="b07">点击我哦</button><br />
	<button id="b08">点击我哦</button><br />	
	<button id="see">看见我不</button><br />
	<button id="b09">点击我哦</button><br />
</div>

<div style="width:300px; text-align:center; padding-top:5px;">
<!-- 如果元素不可见,让其可见 onclick -->
<a href="javascript:void(0)" οnclick="if(!isEleInView('see')) letEleInView('see');">
   如果“看见我不”不在可见区域,则让其可见
</a>
</div>

<script type="text/javascript">
/** 元素是否处于父容器的可见区域 */
function isEleInView(objId){
    // 取得其父容器,此例为指定id的div
    var div = document.getElementById("divScroll");
    var ele = document.getElementById(objId);
	var offsetTopIn = ele.offsetTop - div.offsetTop;
 
	var _scrollTop = div.scrollTop;
	var _scrollHeight = div.scrollHeight;
	var _height = div.clientHeight;
	// 可见范围即父容器滚动条当前位置 至 父容器高度这个范围 
	if(offsetTopIn >= _scrollTop && offsetTopIn <= _scrollTop + _height){ 
	    return true;
	}else{
	    return false;
	}
}

/** 元素置于父容器的可见区域 */
function letEleInView(objId){
    var div = document.getElementById("divScroll");
    var ele = document.getElementById(objId);
	var offsetTopIn = ele.offsetTop - div.offsetTop;
	// 当元素在最后等于同父容器高度的一块内,则置滚动条为最底端即可
	// 否则将滚动条的当前位置置于元素位置。 
	//(当然以下只保留 div.scrollTop = offsetTopIn; 也是可以的,因为滚动条位置超过最大位置时会自动取最大值)
	if(offsetTopIn >= div.scrollHeight - div.clientHeight){
	    div.scrollTop = div.scrollHeight - div.clientHeight;
	}else{
	    div.scrollTop = offsetTopIn;
	}
}
</script>

</body>
</html>



效果如下图:



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值