2

url 中 # (井号, hash)的作用

 2 years ago
source link: https://hellodk.cn/post/860
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

url 中 # (井号, hash)的作用

url 中 # 的作用

# (hash) 代表网页文档中的一个位置,#右边的字符就是该位置的标识符。

# 是用来指导浏览器的动作的,对服务端是无感的。浏览器先请求 url 得到 response 之后再定位到 # 的位置。

为网页位置指定标识符,一般有两种方法

  1. <a name="xxx">position that xxx points</a>
  2. 使用 id 属性

    <div id="xxx">position that xxx points</div>

详细的介绍可以参见 this passage


为我的博客的归档页面添加“年份”的锚点设置

归档页面 url 是 https://hellodk.cn/archives,输入 https://hellodk.cn/archives#2019 在此文发布之前,还不会自动定位到 2019 年发布的文章。现在开始改造。

找到主题下的 page-archives.php,找到如下代码

$output .= '<h3>' . date('Y 年', $archives->created) . '</h3><ul>';

将这一行改成如下代码

$output .= '<h3>' . '<a name="' . $year . '"></a>' . date('Y 年', $archives->created) . '</h3><ul>';

然后保存即可生效。

简单讲解一下作的修改——

h3 标签里要包含一个 a 标签,使用属性 name,值是当前年份(查看上下文能查到变量值是 $year

使用 chrome 打开一个 incognito tab 测试一下访问 https://hellodk.cn/archives#2019 的效果吧~

标签: Typecho, php, web

本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK