1

我发现 SO 的评论可以被锚定并且我很难理解实施。以下链接是锚定评论的示例:

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

根据我对html的理解, html页面中肯定存在comment41994753_26699358after #,但是我没有找到idor 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 ">

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

4

2 回答 2

2

这不是浏览器行为,橙色背景颜色及其滚动到视图中发生在 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);
};
于 2015-06-09T08:44:50.663 回答
2

答案在于onHashChange_HighlightDestinationjavascript 代码中的函数,该函数是从init方法调用的,该方法会在每个请求时触发。

正如您在 javascript 代码的开发人员版中看到的那样,它尝试从请求哈希中提取帖子 ID 和评论 ID:

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

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

于 2015-06-09T08:56:34.707 回答