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



我发现SO的注释可能是锚定的,我很难理解实现。以下链接是锚定评论的示例:

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

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

<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 ">

这个片段只是告诉我两个相对且分离的id id="comment-41994753"id="comments-26699358",最终锚comment41994753_26699358是从它们生成的?或者这是相对于SO使用的框架?

这不是浏览器行为,橙色背景色和滚动到视图中都是用JavaScript实现的。

代码在此文件中:http://cdn.sstatic.net/Js/full.en.js
未缩小的版本:http://dev.stackoverflow.com/content/js/full.js

重要的功能是onHashChange_HighlightDestinationdoHighlight:

onHashChange_HighlightDestination:
它解析散列参数,例如#comment49509148_30726127,然后调用highlight方法。

// 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将注释/答案滚动到视图中。

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方法调用的,该方法在每个请求时都会触发。

正如您在javascript代码的开发人员版本中所看到的,它试图从请求散列中提取post-id和comment-id:

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

从那里它调用highlightComment,它执行scrollIntoView和CSS高亮显示。

最新更新