I have a site with thousands of htm documents on them. Sometimes I need to send someone to a specific paragraph to read. What I am looking for is a jquery plugin which simply adds ids to all the paragraphs, making them linkable, so we could send them to: http://www.demo.com/index.html#p_10 for instance.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
I think what you want is just a simple code like this
jQuery(document).ready(function() {
jQuery('p').each(function(index, value) {
value.id = '_p' + index;
});
$('html, body').animate({
scrollTop: $(window.location.hash).offset().top
}, 500);
});
Here is an example that also displays the id set.
http://jsfiddle.net/ekftprLt/2/
回答2:
Why a plugin? And no need for an ID
This should work if you insert a script into the page or into an existing external script
NOTE: This does NOT modify the DOM in any way and is WAY faster than an .each
$(function() {
var pIndexPos = location.hash.indexOf("p_");
if (pIndexPos!=-1) {
var pIndex = parseInt(location.hash.substring(pIndexPos+2),10)+1; // 1based for nth
var offsetTop = $("p:nth-child("+pIndex+")").offset().top-20; // - height of item
$('html, body').animate({
scrollTop: offsetTop
},500);
}
});