获取锚的偏移位置 [英] Getting anchor's offset position
问题描述
我正在尝试根据用户的选择将窗口滚动到页面上的某个位置.我得到一些奇怪的结果.任何人都可以建议一种更好/更好的方法吗?
I am attempting to scroll the window to a location on my page based on a user's selection. I am getting some strange results. Can anyone suggest a good/better way to go about this?
这就是我正在使用的东西:
Here is what I'm working with:
var rel = $(this).attr('rel');
var citation = rel.split("-")[0];
window.scrollTo(0, $('[name = ' + citation + ' ]').offset().top);
alert($('[name = ' + citation + ' ]').offset().top);
最后一个警报给了我一个似乎错误的数字,并且滚动不起作用.当用户单击文档中的链接时,将执行以下代码.我正在捕获该元素的rel属性值,并(在经过一些字符串操作之后)使用它来查找相应锚点的位置.目标元素的名称属性应与单击的链接的rel属性匹配.明白我的意思吗?
The last alert gives me a number that seems wrong and the scrolling is not working. The following code is executed when the user clicks on a link from within the document. I am capturing that element's rel attribute value and (after a little string manipulation) using it to find the position of the corresponding anchor. The destination element's name attribute should match the rel attribute of the clicked link. See what I mean?
谢谢!
推荐答案
我能够通过不使用offset()而是使用jQuery的position()函数来解决此问题.
I was able to get around this by not using offset() but by rather using jQuery's position() function.
我只是获得返回对象的"top"属性.我必须使用元素的文本作为索引值,因为这些元素没有唯一的ID.
I am just getting the returned object's "top" property. I have to use the element's text as an index value because these elements did not have unique IDs.
var citationIndex = parseInt($(this).text() - 1);
var elementOffset = $('.HwCitationsContent li:eq(' + citationIndex + ')').position().top;
这篇关于获取锚的偏移位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!