简单Js脚本用于Html中绝对位置的控件定位

简单Js脚本用于Html中绝对位置的控件定位

绝对位置定位是在写Html中经常会考虑到的问题,网上也有不少范例,以下的脚本是我根据网上先人和总结下的结果,可用于页面表头为

<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >


的网页,方便可以随时定位div到指定id的控件,以下是脚本内容。

   
// DIV定位函数
function  getAbsolutePosition(obj)
{
position 
=   new  Object();
position.x 
=   0 ;
position.y 
=   0 ;
var  tempobj  =  obj;
    
while (tempobj != null   &&  tempobj != document.body)
    
{
        
if (window.navigator.userAgent.indexOf( " MSIE " ) !=- 1 )
        
{
            position.x 
+=  tempobj.offsetLeft + 10 ;
            position.y 
+=  tempobj.offsetTop + 15 ;
        }

        
else   if (window.navigator.userAgent.indexOf( " Firefox " ) !=- 1 )
        
{
            position.x 
+=  tempobj.offsetLeft;
            position.y 
+=  tempobj.offsetTop;
        }

        tempobj 
=  tempobj.offsetParent
    }

return  position;
}


     可用于IE和Firefox浏览器获取绝对位置。然后设置div或者其他控件的位置于该控件上.

 
function  SetnPos()
{
var  pos = getAbsolutePosition(document.getElementById( " txt_box " ));
document.getElementById(
" dv_div " ).style.left = pos.x + " px " ;
document.getElementById(
" dv_dvab " ).style.top = pos.y + " px " ;
}


注意:
1.被定位的层必须是style="position:absolute "
2.如果在.net 2.0 母子版面的页面设计中,必须将函数放于masterpage中,放在子页面定位将会定位错误,因为子页面获取不到全部的页面.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值