jQuery Offset returns negative value

末鹿安然 提交于 2019-12-07 05:36:06

问题


am having a scenario like this below:

In my ui, I will have a textbox. If I have enter a number in the textbox,I need to scroll down to the respective page number.

In Dom, I will have some divs with the respective id's. If user entered a page number as 5. I will check for 5th div offset in dom and get top value. By using scrollTop It will scrolled to the 5th div.

Here, Issue is after scrolled down to the 5th div. If again, entered a page number as 2. offset top value in negative. Hence,ScrollTop defaultly moved to top.

Here is fiddle

To reproduce this exactly,Go to page number 7 and again go to page number 3 or 4.


回答1:


http://jsfiddle.net/Ldfmvwr9/3/

Try it

topValue=$('#container').scrollTop() + $("#"+parseInt(userPageNum)).offset().top - $("#"+parseInt(userPageNum)).height() / 2;



回答2:


Late answer, in case it will help someone:

Just use dom offsetTop property. That will be a correct position despite whatever scrolling has happened before.

$( something )[0].offsetTop; 


来源:https://stackoverflow.com/questions/27632300/jquery-offset-returns-negative-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!