现在的位置: 首页 > 综合 > 正文

how to focus to a div both in firefox and IE

2011年07月14日 ⁄ 综合 ⁄ 共 688字 ⁄ 字号 评论关闭
The following code work well in IE to focus to a div:

document.getElementById("div1").focus();

However, it doesn't work in firefox. You will not see any action taken after the line is executed. To workaround the issue, you can use the following code:

function getOffsetTop(el)
{
    
var yPos = el.offsetTop;
    
var tempEl = el.offsetParent;
    
while (tempEl != null)
    
{
        yPos 
+= tempEl.offsetTop;
        tempEl 
= tempEl.offsetParent;
    }

    
return yPos; 
}


window.scrollTo(
0,getOffsetTop(e)); 

getOffsetTop method is used to get the accurate top pixel of any element.

Here, window.scrollTo has two parameters. The first one represents offsetX and the second one represents offsetY. Here we only use the second parameter to scroll to the top border of the target control.

抱歉!评论已关闭.