开发者

Javascript Scroll Past Hash

I have a fixed div at the top of my page and a list of links somewhat far开发者_Python百科ther down the page. There is a link the user can click that runs onclick:

function setOffset(){   
location.hash = offset;  //where offset is some number I want as the hash  
scrollTo(0, 40);  
}  

What I want to happen is to jump to the hashed link, then scroll an extra 40 to bring the item into view and out from under the fixed div. The problem is scrollTo jumps to the top of the page and kills the hash. Anyone have any ideas?


http://www.w3schools.com/jsref/met_win_scrollto.asp

scrollTo(xPos, yPos)

So in your code:

scrollTo(0, 40);

says to scroll to x-position of 0 (which is the left) and y-position 40 (which is 40 pixels down from the top). You will need to calculate the position of your hash then add 40 to it, to scroll an additional 40 pixels. You can get the position of an element on your page by it's offSetTop property I believe.

HTH.

Edit: So it looks like in your example you already have an offset, which I am presuming is the offset of the element you are trying to scroll to, so your code will look like this:

function setOffset(){   
scrollTo(0,offset + 40); 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜