StackOverflow 评论的 html 锚点,例如 "http://SO/...#comment41994753_26699358"

StackOverflow comment's html anchor such as "http://SO/...#comment41994753_26699358"

我发现 SO 的注释可以锚定,但我很难理解该实现。以下link为an example锚定评论:

http://SO/questions/26696064/slug/26699358?noredirect=1#comment41994753_26699358

根据我对html的理解,#之后的comment41994753_26699358一定存在于html页面中,但是我没有找到id或者name 在里面。当我阅读源代码时,我只找到相对的源代码:

<div id="comments-26699358" class="comments ">
        <table>
            <tbody data-remaining-comments-count="0" data-canpost="true" data-cansee="false" data-comments-unavailable="false" data-addlink-disabled="false">
               <tr id="comment-41994753" class="comment ">

这个片段只告诉我两个相对和分开的ids id="comment-41994753"id="comments-26699358",最终的锚点comment41994753_26699358是从它们生成的?或者这与所使用的框架有关?

这不是浏览器行为,橙色背景颜色及其滚动到视图中发生 JavaScript。

代码在这个文件中:http://cdn.sstatic.net/Js/full.en.js
非缩小版:http://dev.whosebug.com/content/js/full.js

重要的函数是onHashChange_HighlightDestinationdoHighlight:

onHashChange_HighlightDestination:
它解析散列参数,e。 G。 #comment49509148_30726127 然后调用高亮方法。

// answers have the form 'lies-like/58534#58534'; comments are 'lies-like/58534#comment60949_58534'
var match = decodeURI(url).match(/#(\d+|comment(\d+)_(\d+))/i);
if (!match) return; // moderator viewing a flagged question, e.g. 'lies-like#question'

if (match[2])
    highlightComment(match[2], match[3]);
else
    highlightAnswer(match[1]);

doHighlight:此方法最终突出显示它(橙色背景)并使用函数 scrollIntoView.

将 comment/answer 滚动到视图中
var doHighlight = function (jEle) {
    var originalColor = backgroundColor;
    jEle
        .css({ backgroundColor: highlightColor })
        .animate({ backgroundColor: originalColor }, 2000, 'linear', function () { $(this).css('background-color', ''); });

    if (jEle.is('.comment'))
        jEle[0].scrollIntoView(true);
};

答案在于 javascript 代码中的 onHashChange_HighlightDestination 函数,它是从 init 方法中调用的,该方法在每次请求时都会触发。

如您在 developer edition of the javascript code 中所见,它尝试从请求哈希中提取 post id 和评论 id:

var match = decodeURI(url).match(/#(\d+|comment(\d+)_(\d+))/i);

从那里调用 highlightCommentscrollIntoView 和 CSS 突出显示。