Hexo 博客主页设置访客欢迎栏

以下是最新版 card-welcome.js 完整代码,支持中英文地名自动映射、直辖市智能识别、逐行动画效果。直接复制使用,只需修改顶部 BLOG_LOCATION 的经纬度为你的位置即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
window.IP_CONFIG = {
// API_KEY: '848dbcf5d47e39c6', // API密钥 申请地址:https://api.76.al/ 已失效
BLOG_LOCATION: {
lng: 121.4581, // 经度
lat: 31.2222 // 纬度
},
CACHE_DURATION: 1000 * 60 * 60, // 可配置缓存时间(默认1小时)
HOME_PAGE_ONLY: true, // 是否只在首页显示 开启后其它页面将不会显示这个容器
};

const insertAnnouncementComponent = () => {
const announcementCards = document.querySelectorAll('.card-widget.card-announcement');
if (!announcementCards.length) return;

if (IP_CONFIG.HOME_PAGE_ONLY && !isHomePage()) {
announcementCards.forEach(card => card.remove());
return;
}

if (!document.querySelector('#welcome-info')) return;
fetchIpInfo();
};

const getWelcomeInfoElement = () => document.querySelector('#welcome-info');

const fetchIpData = async () => {
const response = await fetch('https://ipapi.co/json/');
if (!response.ok) throw new Error('网络响应不正常');
const data = await response.json();

if (data && !data.error) {
return {
data: {
lng: data.longitude,
lat: data.latitude,
country: data.country_name,
prov: data.region,
city: data.city
},
ip: data.ip
};
}
throw new Error('获取位置信息失败');
};

const showWelcome = ({
data,
ip
}) => {
if (!data) return showErrorMessage();

const {
lng,
lat,
country,
prov,
city
} = data;
const welcomeInfo = getWelcomeInfoElement();
if (!welcomeInfo) return;

const dist = calculateDistance(lng, lat);
const ipDisplay = formatIpDisplay(ip);
const pos = formatLocation(country, prov, city);

welcomeInfo.style.display = 'block';
welcomeInfo.style.height = 'auto';
welcomeInfo.innerHTML = generateWelcomeMessage(pos, dist, ipDisplay, country, prov, city);
};

const calculateDistance = (lng, lat) => {
const R = 6371;
const rad = Math.PI / 180;
const dLat = (lat - IP_CONFIG.BLOG_LOCATION.lat) * rad;
const dLon = (lng - IP_CONFIG.BLOG_LOCATION.lng) * rad;
const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(IP_CONFIG.BLOG_LOCATION.lat * rad) * Math.cos(lat * rad) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);

return Math.round(R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)));
};

const formatIpDisplay = (ip) => ip.includes(":") ? "<br>好复杂,咱看不懂~(ipv6)" : ip;

const countryNameMap = {
"China": "中国", "United States": "美国", "Japan": "日本",
"Russia": "俄罗斯", "France": "法国", "Germany": "德国",
"Australia": "澳大利亚", "Canada": "加拿大", "United Kingdom": "英国",
"South Korea": "韩国", "India": "印度", "Brazil": "巴西",
"Singapore": "新加坡", "Thailand": "泰国", "Malaysia": "马来西亚",
"Indonesia": "印度尼西亚", "Vietnam": "越南", "Philippines": "菲律宾",
"New Zealand": "新西兰", "Italy": "意大利", "Spain": "西班牙",
"Netherlands": "荷兰", "Sweden": "瑞典", "Switzerland": "瑞士",
"Taiwan": "中国台湾", "Hong Kong": "中国香港", "Macau": "中国澳门"
};

const toChineseCountry = (country) => countryNameMap[country] || country;

const provinceNameMap = {
"Beijing": "北京市", "Tianjin": "天津市", "Hebei": "河北省", "Shanxi": "山西省",
"Inner Mongolia": "内蒙古自治区", "Liaoning": "辽宁省", "Jilin": "吉林省",
"Heilongjiang": "黑龙江省", "Shanghai": "上海市", "Jiangsu": "江苏省",
"Zhejiang": "浙江省", "Anhui": "安徽省", "Fujian": "福建省", "Jiangxi": "江西省",
"Shandong": "山东省", "Henan": "河南省", "Hubei": "湖北省", "Hunan": "湖南省",
"Guangdong": "广东省", "Guangxi": "广西壮族自治区", "Hainan": "海南省",
"Sichuan": "四川省", "Guizhou": "贵州省", "Yunnan": "云南省", "Tibet": "西藏自治区",
"Shaanxi": "陕西省", "Gansu": "甘肃省", "Qinghai": "青海省",
"Ningxia": "宁夏回族自治区", "Xinjiang": "新疆维吾尔自治区", "Taiwan": "台湾省",
"Hong Kong": "香港特别行政区", "Macau": "澳门特别行政区",
"Heilongjiang Sheng": "黑龙江省", "Urumqi": "新疆维吾尔自治区",
"Hong Kong SAR": "香港特别行政区", "Macao SAR": "澳门特别行政区"
};

const toChineseProvince = (prov) => provinceNameMap[prov] || prov;

const cityNameMap = {
"Beijing": "北京", "Tianjin": "天津", "Shanghai": "上海", "Chongqing": "重庆",
"Shijiazhuang": "石家庄", "Tangshan": "唐山", "Qinhuangdao": "秦皇岛",
"Handan": "邯郸", "Xingtai": "邢台", "Baoding": "保定", "Zhangjiakou": "张家口",
"Chengde": "承德", "Cangzhou": "沧州", "Langfang": "廊坊", "Hengshui": "衡水",
"Taiyuan": "太原", "Datong": "大同", "Changzhi": "长治", "Yuncheng": "运城",
"Hohhot": "呼和浩特", "Baotou": "包头", "Ordos": "鄂尔多斯", "Shenyang": "沈阳",
"Dalian": "大连", "Anshan": "鞍山", "Fushun": "抚顺", "Changchun": "长春",
"Harbin": "哈尔滨", "Nanjing": "南京", "Suzhou": "苏州", "Wuxi": "无锡",
"Changzhou": "常州", "Nantong": "南通", "Yangzhou": "扬州", "Xuzhou": "徐州",
"Hangzhou": "杭州", "Ningbo": "宁波", "Wenzhou": "温州", "Jiaxing": "嘉兴",
"Hefei": "合肥", "Wuhu": "芜湖", "Bengbu": "蚌埠", "Fuzhou": "福州",
"Xiamen": "厦门", "Quanzhou": "泉州", "Nanchang": "南昌", "Ganzhou": "赣州",
"Jinan": "济南", "Qingdao": "青岛", "Yantai": "烟台", "Zhengzhou": "郑州",
"Luoyang": "洛阳", "Kaifeng": "开封", "Xinyang": "信阳", "Nanyang": "南阳",
"Zhumadian": "驻马店", "Wuhan": "武汉", "Huanggang": "黄冈", "Changsha": "长沙",
"Zhuzhou": "株洲", "Guangzhou": "广州", "Shenzhen": "深圳", "Dongguan": "东莞",
"Foshan": "佛山", "Zhuhai": "珠海", "Shantou": "汕头", "Yangjiang": "阳江",
"Nanning": "南宁", "Guilin": "桂林", "Haikou": "海口", "Sanya": "三亚",
"Chengdu": "成都", "Mianyang": "绵阳", "Guiyang": "贵阳", "Kunming": "昆明",
"Lhasa": "拉萨", "Xi'an": "西安", "Xianyang": "咸阳", "Lanzhou": "兰州",
"Xining": "西宁", "Yinchuan": "银川", "Urumqi": "乌鲁木齐", "Tokyo": "东京",
"Osaka": "大阪", "Seoul": "首尔", "Bangkok": "曼谷", "Singapore": "新加坡",
"New York": "纽约", "Los Angeles": "洛杉矶", "San Francisco": "旧金山",
"London": "伦敦", "Paris": "巴黎", "Berlin": "柏林", "Moscow": "莫斯科",
"Sydney": "悉尼", "Melbourne": "墨尔本", "Toronto": "多伦多"
};

const toChineseCity = (city) => cityNameMap[city] || city;

const directAdminMunicipalities = ["北京市", "天津市", "上海市", "重庆市"];

const formatLocation = (country, prov, city) => {
const cnCountry = toChineseCountry(country);
const cnProv = toChineseProvince(prov);
const cnCity = toChineseCity(city);
if (cnCountry === "中国") {
return directAdminMunicipalities.includes(cnProv) ? cnProv : `${cnProv} ${cnCity}`;
}
return cnCountry || '神秘地区';
};

const generateWelcomeMessage = (pos, dist, ipDisplay, country, prov, city) => `
<div class="welcome-content">
<div class="welcome-line welcome-location">✨ 欢迎来自 <b>${pos}</b> 的朋友</div>
<div class="welcome-line welcome-time">${getTimeGreeting()}</div>
<div class="welcome-line welcome-distance">📍 距博主约 <b>${dist}</b> 公里</div>
<div class="welcome-line welcome-greeting">💫 <b>${getGreeting(country, prov, city)}</b></div>
</div>
`;

const addStyles = () => {
const style = document.createElement('style');
style.textContent = `
#welcome-info {
user-select: none;
display: flex;
justify-content: center;
align-items: center;
min-height: 180px;
padding: 20px 16px;
margin-top: 8px;
border-radius: 14px;
background: linear-gradient(135deg, var(--anzhiyu-background) 0%, var(--anzhiyu-card-bg, var(--anzhiyu-background)) 100%);
outline: 1px solid var(--anzhiyu-card-border);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
transition: box-shadow 0.3s ease;
}
#welcome-info:hover {
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}
.welcome-content {
text-align: center;
line-height: 1.8;
font-size: 14px;
}
.welcome-line {
margin: 4px 0;
animation: fadeInUp 0.5s ease forwards;
opacity: 0;
}
.welcome-location {
animation-delay: 0.1s;
font-size: 16px;
white-space: nowrap;
}
.welcome-time {
animation-delay: 0.2s;
font-size: 15px;
}
.welcome-distance {
animation-delay: 0.3s;
font-size: 14px;
color: var(--anzhiyu-font-color, #666);
}
.welcome-greeting {
animation-delay: 0.4s;
font-size: 14px;
margin-top: 6px;
padding-top: 6px;
border-top: 1px dashed var(--anzhiyu-card-border);
color: var(--anzhiyu-main);
white-space: nowrap;
}
.welcome-line b {
color: var(--anzhiyu-main);
}
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(8px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.loading-spinner {
width: 40px;
height: 40px;
border: 3px solid rgba(0, 0, 0, 0.06);
border-radius: 50%;
border-top-color: var(--anzhiyu-main);
animation: spin 0.8s linear infinite;
}
@keyframes spin {
100% { transform: rotate(360deg); }
}
.error-message {
color: #ff6565;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 8px;
}
.error-message p,
.permission-dialog p {
margin: 0;
}
.error-icon {
font-size: 2.5rem;
}
#retry-button {
margin: 0 4px;
color: var(--anzhiyu-main);
cursor: pointer;
transition: transform 0.3s ease;
}
#retry-button:hover {
transform: rotate(180deg);
}
.permission-dialog {
text-align: center;
}
.permission-dialog button {
margin: 10px 6px;
padding: 8px 20px;
border: none;
border-radius: 20px;
background-color: var(--anzhiyu-main);
color: white;
font-size: 14px;
cursor: pointer;
transition: all 0.3s ease;
}
.permission-dialog button:hover {
transform: translateY(-2px);
opacity: 0.9;
}
.permission-dialog button[data-action="deny"] {
background-color: transparent;
color: var(--anzhiyu-font-color);
border: 1px solid var(--anzhiyu-card-border);
box-shadow: none;
}
.permission-dialog button[data-action="deny"]:hover {
background-color: var(--anzhiyu-background);
transform: translateY(-2px);
}
`;
document.head.appendChild(style);
};

const checkLocationPermission = () => localStorage.getItem('locationPermission') === 'granted';
const saveLocationPermission = (permission) => {
localStorage.setItem('locationPermission', permission);
};
const showLocationPermissionDialog = () => {
const welcomeInfoElement = document.getElementById("welcome-info");
welcomeInfoElement.innerHTML = `
<div class="permission-dialog">
<div class="error-icon">❓</div>
<p>是否允许访问您的位置信息?</p>
<button data-action="allow">允许</button>
<button data-action="deny">拒绝</button>
</div>
`;

welcomeInfoElement.addEventListener('click', (e) => {
if (e.target.tagName === 'BUTTON') {
const action = e.target.dataset.action;
const permission = action === 'allow' ? 'granted' : 'denied';
handleLocationPermission(permission);
}
});
};
const handleLocationPermission = (permission) => {
saveLocationPermission(permission);
if (permission === 'granted') {
showLoadingSpinner();
fetchIpInfo();
} else {
showErrorMessage('您已拒绝访问位置信息');
}
};

const showLoadingSpinner = () => {
const welcomeInfoElement = document.querySelector("#welcome-info");
if (!welcomeInfoElement) return;
welcomeInfoElement.innerHTML = '<div class="loading-spinner"></div>';
};

const IP_CACHE_KEY = 'ip_info_cache';
const getIpInfoFromCache = () => {
const cached = localStorage.getItem(IP_CACHE_KEY);
if (!cached) return null;

const { data, timestamp } = JSON.parse(cached);
if (Date.now() - timestamp > IP_CONFIG.CACHE_DURATION) {
localStorage.removeItem(IP_CACHE_KEY);
return null;
}
return data;
};
const setIpInfoCache = (data) => {
localStorage.setItem(IP_CACHE_KEY, JSON.stringify({
data,
timestamp: Date.now()
}));
};

const fetchIpInfo = async () => {
if (!checkLocationPermission()) {
showLocationPermissionDialog();
return;
}

showLoadingSpinner();

const cachedData = getIpInfoFromCache();
if (cachedData) {
showWelcome(cachedData);
return;
}

try {
const data = await fetchIpData();
setIpInfoCache(data);
showWelcome(data);
} catch (error) {
console.error('获取IP信息失败:', error);
showErrorMessage();
}
};

const greetings = {
"中国": {
"北京市": "北——京——欢迎你~~~",
"天津市": "讲段相声吧",
"河北省": "山势巍巍成壁垒,天下雄关铁马金戈由此向,无限江山",
"山西省": "展开坐具长三尺,已占山河五百余",
"内蒙古自治区": "天苍苍,野茫茫,风吹草低见牛羊",
"辽宁省": "我想吃烤鸡架!",
"吉林省": "状元阁就是东北烧烤之王",
"黑龙江省": "很喜欢哈尔滨大剧院",
"上海市": "众所周知,中国只有两个城市",
"江苏省": {
"南京市": "这是我挺想去的城市啦",
"苏州市": "上有天堂,下有苏杭",
"其他": "散装是必须要散装的"
},
"浙江省": {
"杭州市": "东风渐绿西湖柳,雁已还人未南归",
"其他": "望海楼明照曙霞,护江堤白蹋晴沙"
},
"河南省": {
"郑州市": "豫州之域,天地之中",
"信阳市": "品信阳毛尖,悟人间芳华",
"南阳市": "臣本布衣,躬耕于南阳此南阳非彼南阳!",
"驻马店市": "峰峰有奇石,石石挟仙气嵖岈山的花很美哦!",
"开封市": "刚正不阿包青天",
"洛阳市": "洛阳牡丹甲天下",
"其他": "可否带我品尝河南烩面啦?"
},
"安徽省": "蚌埠住了,芜湖起飞",
"福建省": "井邑白云间,岩城远带山",
"江西省": "落霞与孤鹜齐飞,秋水共长天一色",
"山东省": "遥望齐州九点烟,一泓海水杯中泻",
"湖北省": {
"黄冈市": "红安将军县!辈出将才!",
"其他": "来碗热干面~"
},
"湖南省": "74751,长沙斯塔克",
"广东省": {
"广州市": "看小蛮腰,喝早茶了嘛~",
"深圳市": "今天你逛商场了嘛~",
"阳江市": "阳春合水!博主家乡~ 欢迎来玩~",
"其他": "来两斤福建人~"
},
"广西壮族自治区": "桂林山水甲天下",
"海南省": "朝观日出逐白浪,夕看云起收霞光",
"四川省": "康康川妹子",
"贵州省": "茅台,学生,再塞200",
"云南省": "玉龙飞舞云缠绕,万仞冰川直耸天",
"西藏自治区": "躺在茫茫草原上,仰望蓝天",
"陕西省": "来份臊子面加馍",
"甘肃省": "羌笛何须怨杨柳,春风不度玉门关",
"青海省": "牛肉干和老酸奶都好好吃",
"宁夏回族自治区": "大漠孤烟直,长河落日圆",
"新疆维吾尔自治区": "驼铃古道丝绸路,胡马犹闻唐汉风",
"台湾省": "我在这头,大陆在那头",
"香港特别行政区": "永定贼有残留地鬼嚎,迎击光非岁玉",
"澳门特别行政区": "性感荷官,在线发牌",
"其他": "带我去你的城市逛逛吧!"
},
"美国": "Let us live in peace!",
"日本": "よろしく、一緒に桜を見ませんか",
"俄罗斯": "干了这瓶伏特加!",
"法国": "C'est La Vie",
"德国": "Die Zeit verging im Fluge.",
"澳大利亚": "一起去大堡礁吧!",
"加拿大": "拾起一片枫叶赠予你",
"其他": "带我去你的国家逛逛吧"
};

const getGreeting = (country, province, city) => {
const cnCountry = toChineseCountry(country);
const cnProv = toChineseProvince(province);
const cnCity = toChineseCity(city);
const countryGreeting = greetings[cnCountry] || greetings["其他"];
if (typeof countryGreeting === 'string') {
return countryGreeting;
}
const provinceGreeting = countryGreeting[cnProv] || countryGreeting["其他"];
if (typeof provinceGreeting === 'string') {
return provinceGreeting;
}
return provinceGreeting[cnCity] || provinceGreeting["其他"] || countryGreeting["其他"];
};

const getTimeGreeting = () => {
const hour = new Date().getHours();
if (hour < 11) return "🌅 早上好,一日之计在于晨";
if (hour < 13) return "☀️ 中午好,记得午休喔~";
if (hour < 17) return "🍵 下午好,记得多喝水!";
if (hour < 19) return "🌇 即将下班,记得按时吃饭~";
return "🌙 晚上好,夜生活来咯!";
};

const showErrorMessage = (message = '抱歉,无法获取信息') => {
const welcomeInfoElement = document.getElementById("welcome-info");
welcomeInfoElement.innerHTML = `
<div class="error-message">
<div class="error-icon">😕</div>
<p>${message}</p>
<p>请<i id="retry-button" class="fa-solid fa-arrows-rotate"></i>重试或检查网络连接</p>
</div>
`;

document.getElementById('retry-button').addEventListener('click', fetchIpInfo);
};

const isHomePage = () => {
return window.location.pathname === '/' || window.location.pathname === '/index.html';
};

document.addEventListener('DOMContentLoaded', () => {
addStyles();
insertAnnouncementComponent();
document.addEventListener('pjax:complete', insertAnnouncementComponent);
});

最近在交流群里发现很多人都在折腾怎么在公告栏显示访客欢迎语,感觉效果还不错,我也来折腾一下。

踩坑记录

在使用过程中遇到了几个问题,记录一下解决方案。

问题一:国家/省份/城市显示为英文

现象:欢迎栏显示”欢迎来自 China Guangdong Shenzhen 的朋友”,国家、省份、城市名都是英文。

原因:使用的 ipapi.co 接口返回的 country_nameregioncity 字段都是英文,而 greetings 对象的 key 是中文(如 "中国""广东省"),导致匹配不上,欢迎词无法正确显示。

解决方案:添加三张映射表,将英文名转换为中文:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const countryNameMap = {
"China": "中国", "United States": "美国", "Japan": "日本",
"Russia": "俄罗斯", "France": "法国", "Germany": "德国",
"Australia": "澳大利亚", "Canada": "加拿大", "United Kingdom": "英国",
"South Korea": "韩国", "India": "印度", "Brazil": "巴西",
"Singapore": "新加坡", "Thailand": "泰国", "Malaysia": "马来西亚",
// ...更多国家
};

const provinceNameMap = {
"Beijing": "北京市", "Tianjin": "天津市", "Hebei": "河北省",
"Shanxi": "山西省", "Inner Mongolia": "内蒙古自治区",
"Liaoning": "辽宁省", "Jilin": "吉林省", "Heilongjiang": "黑龙江省",
"Shanghai": "上海市", "Jiangsu": "江苏省", "Zhejiang": "浙江省",
// ...更多省份
};

const cityNameMap = {
"Beijing": "北京", "Shanghai": "上海", "Guangzhou": "广州",
"Shenzhen": "深圳", "Hangzhou": "杭州", "Nanjing": "南京",
"Tokyo": "东京", "New York": "纽约", "London": "伦敦",
// ...更多城市
};

const toChineseCountry = (country) => countryNameMap[country] || country;
const toChineseProvince = (prov) => provinceNameMap[prov] || prov;
const toChineseCity = (city) => cityNameMap[city] || city;

formatLocationgetGreeting 函数中调用映射:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const formatLocation = (country, prov, city) => {
const cnCountry = toChineseCountry(country);
const cnProv = toChineseProvince(prov);
const cnCity = toChineseCity(city);
if (cnCountry === "中国") {
return `${cnProv} ${cnCity}`;
}
return cnCountry || '神秘地区';
};

const getGreeting = (country, province, city) => {
const cnCountry = toChineseCountry(country);
const cnProv = toChineseProvince(province);
const cnCity = toChineseCity(city);
// ...用中文 key 查找 greetings 对象
};

问题二:直辖市显示冗余

现象:上海用户显示”上海市 上海”,北京用户显示”北京市 北京”,重复了。

原因:直辖市的省份名本身就包含”市”,不需要再拼接城市名。

解决方案:判断是否为直辖市,是则直接返回省份名:

1
2
3
4
5
6
7
8
9
10
11
12
13
const directAdminMunicipalities = ["北京市", "天津市", "上海市", "重庆市"];

const formatLocation = (country, prov, city) => {
const cnCountry = toChineseCountry(country);
const cnProv = toChineseProvince(prov);
const cnCity = toChineseCity(city);
if (cnCountry === "中国") {
return directAdminMunicipalities.includes(cnProv)
? cnProv
: `${cnProv} ${cnCity}`;
}
return cnCountry || '神秘地区';
};

问题三:欢迎词换行导致排版错乱

现象:较长的欢迎词(如”众所周知,中国只有两个城市”)被 <br> 换行截断,显示为两行,整体不美观。

原因:模板中使用纯 <br> 换行,且欢迎词没有限制不换行,长文本会自动折行。

解决方案:用 <div> 替代纯文本 + <br>,并给欢迎词加 white-space: nowrap

1
2
3
4
5
6
7
8
9
10
11
const generateWelcomeMessage = (pos, dist, ipDisplay, country, prov, city) => `
<div class="welcome-content">
<div class="welcome-line welcome-location">🎊 欢迎来自 <b>${pos}</b> 的朋友</div>
<div class="welcome-line welcome-row">
<span class="welcome-time">${getTimeGreeting()}</span>
<span class="welcome-sep">|</span>
<span class="welcome-distance">📏 距博主约 <b>${dist}</b> 公里</span>
</div>
<div class="welcome-line welcome-greeting">🎀 <b>${getGreeting(country, prov, city)}</b></div>
</div>
`;

同时将时间问候和距离合并为一行显示,欢迎词加 white-space: nowrap 防止折行。

问题四:界面不够美观

现象:欢迎栏样式较为朴素,缺乏层次感。

解决方案:对 CSS 样式进行了美化:

  • 卡片增加渐变背景和 hover 阴影效果
  • 各行内容添加 fadeInUp 逐行动画
  • 时间 + 距离用 flexbox 横向排列,中间用竖线分隔
  • 欢迎词用虚线分隔 + 主题色高亮
  • 权限弹窗按钮改为胶囊形,拒绝按钮改为描边风格
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#welcome-info {
border-radius: 14px;
background: linear-gradient(135deg, var(--anzhiyu-background) 0%, var(--anzhiyu-card-bg, var(--anzhiyu-background)) 100%);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
transition: box-shadow 0.3s ease;
}
#welcome-info:hover {
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}
.welcome-line {
animation: fadeInUp 0.5s ease forwards;
opacity: 0;
}
.welcome-greeting {
white-space: nowrap;
border-top: 1px dashed var(--anzhiyu-card-border);
}
@keyframes fadeInUp {
from { opacity: 0; transform: translateY(8px); }
to { opacity: 1; transform: translateY(0); }
}

方案一

image-20241216160329859

给主题添加来访者卡片

效果预览

image-20241213172530293

配置步骤

安知鱼主题

申请API密钥

注册青桔API,到密钥管理申请API_KEY即可,目前我们使用到的API是完全免费且无次数限制的。

现改用免费的 ip-api.com

现改用免费的 ipapi.co(支持 HTTPS,无需 API Key)

创建JS文件

在博客目录的 source 文件夹下创建 card-welcome.js 文件(也可以在source文件夹下另外新建文件夹)。

将以下内容复制到 card-welcome.js 中,并修改文件顶部配置信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
window.IP_CONFIG = {
// API_KEY: '848dbcf5d47e39c6', // API密钥 申请地址:https://api.76.al/ 已失效
BLOG_LOCATION: {
lng: 121.4581, // 经度
lat: 31.2222 // 纬度
},
CACHE_DURATION: 1000 * 60 * 60, // 可配置缓存时间(默认1小时)
HOME_PAGE_ONLY: true, // 是否只在首页显示 开启后其它页面将不会显示这个容器
};

const insertAnnouncementComponent = () => {
// 获取所有公告卡片
const announcementCards = document.querySelectorAll('.card-widget.card-announcement');
if (!announcementCards.length) return;

if (IP_CONFIG.HOME_PAGE_ONLY && !isHomePage()) {
announcementCards.forEach(card => card.remove());
return;
}

if (!document.querySelector('#welcome-info')) return;
fetchIpInfo();
};

const getWelcomeInfoElement = () => document.querySelector('#welcome-info');

// const fetchIpData = async () => {
// const response = await fetch(`https://api.nsmao.net/api/ip/query?key=${encodeURIComponent(IP_CONFIG.API_KEY)}`);
// if (!response.ok) throw new Error('网络响应不正常');
// return await response.json();
// };

// const fetchIpData = async () => {
// // 使用免费的ip-api.com(不需要key,限制每分钟45次请求)
// const response = await fetch('https://ip-api.com/json/');
// if (!response.ok) throw new Error('网络响应不正常');
// const data = await response.json();

// if (data.status === 'success') {
// return {
// data: {
// lng: data.lon,
// lat: data.lat,
// country: data.country,
// prov: data.regionName,
// city: data.city
// },
// ip: data.query
// };
// }
// throw new Error('获取位置信息失败');
// };


const fetchIpData = async () => {
// 使用 ipapi.co 的 HTTPS 接口(免费版有限制)
const response = await fetch('https://ipapi.co/json/');
if (!response.ok) throw new Error('网络响应不正常');
const data = await response.json();

if (data && !data.error) {
return {
data: {
lng: data.longitude,
lat: data.latitude,
country: data.country_name,
prov: data.region,
city: data.city
},
ip: data.ip
};
}
throw new Error('获取位置信息失败');
};

const showWelcome = ({
data,
ip
}) => {
if (!data) return showErrorMessage();

const {
lng,
lat,
country,
prov,
city
} = data;
const welcomeInfo = getWelcomeInfoElement();
if (!welcomeInfo) return;

const dist = calculateDistance(lng, lat);
const ipDisplay = formatIpDisplay(ip);
const pos = formatLocation(country, prov, city);

welcomeInfo.style.display = 'block';
welcomeInfo.style.height = 'auto';
welcomeInfo.innerHTML = generateWelcomeMessage(pos, dist, ipDisplay, country, prov, city);
};

const calculateDistance = (lng, lat) => {
const R = 6371; // 地球半径(km)
const rad = Math.PI / 180;
const dLat = (lat - IP_CONFIG.BLOG_LOCATION.lat) * rad;
const dLon = (lng - IP_CONFIG.BLOG_LOCATION.lng) * rad;
const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(IP_CONFIG.BLOG_LOCATION.lat * rad) * Math.cos(lat * rad) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);

return Math.round(R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)));
};
const formatIpDisplay = (ip) => ip.includes(":") ? "<br>好复杂,咱看不懂~(ipv6)" : ip;
const countryNameMap = {
"China": "中国", "United States": "美国", "Japan": "日本",
"Russia": "俄罗斯", "France": "法国", "Germany": "德国",
"Australia": "澳大利亚", "Canada": "加拿大", "United Kingdom": "英国",
"South Korea": "韩国", "India": "印度", "Brazil": "巴西",
"Singapore": "新加坡", "Thailand": "泰国", "Malaysia": "马来西亚",
"Indonesia": "印度尼西亚", "Vietnam": "越南", "Philippines": "菲律宾",
"New Zealand": "新西兰", "Italy": "意大利", "Spain": "西班牙",
"Netherlands": "荷兰", "Sweden": "瑞典", "Switzerland": "瑞士",
"Taiwan": "中国台湾", "Hong Kong": "中国香港", "Macau": "中国澳门"
};

const toChineseCountry = (country) => countryNameMap[country] || country;

const provinceNameMap = {
"Beijing": "北京市", "Tianjin": "天津市", "Hebei": "河北省", "Shanxi": "山西省",
"Inner Mongolia": "内蒙古自治区", "Liaoning": "辽宁省", "Jilin": "吉林省",
"Heilongjiang": "黑龙江省", "Shanghai": "上海市", "Jiangsu": "江苏省",
"Zhejiang": "浙江省", "Anhui": "安徽省", "Fujian": "福建省", "Jiangxi": "江西省",
"Shandong": "山东省", "Henan": "河南省", "Hubei": "湖北省", "Hunan": "湖南省",
"Guangdong": "广东省", "Guangxi": "广西壮族自治区", "Hainan": "海南省",
"Sichuan": "四川省", "Guizhou": "贵州省", "Yunnan": "云南省", "Tibet": "西藏自治区",
"Shaanxi": "陕西省", "Gansu": "甘肃省", "Qinghai": "青海省",
"Ningxia": "宁夏回族自治区", "Xinjiang": "新疆维吾尔自治区", "Taiwan": "台湾省",
"Hong Kong": "香港特别行政区", "Macau": "澳门特别行政区",
"Heilongjiang Sheng": "黑龙江省", "Urumqi": "新疆维吾尔自治区",
"Hong Kong SAR": "香港特别行政区", "Macao SAR": "澳门特别行政区"
};

const toChineseProvince = (prov) => provinceNameMap[prov] || prov;

const cityNameMap = {
"Beijing": "北京", "Tianjin": "天津", "Shanghai": "上海", "Chongqing": "重庆",
"Shijiazhuang": "石家庄", "Tangshan": "唐山", "Qinhuangdao": "秦皇岛",
"Handan": "邯郸", "Xingtai": "邢台", "Baoding": "保定", "Zhangjiakou": "张家口",
"Chengde": "承德", "Cangzhou": "沧州", "Langfang": "廊坊", "Hengshui": "衡水",
"Taiyuan": "太原", "Datong": "大同", "Changzhi": "长治", "Yuncheng": "运城",
"Hohhot": "呼和浩特", "Baotou": "包头", "Ordos": "鄂尔多斯", "Shenyang": "沈阳",
"Dalian": "大连", "Anshan": "鞍山", "Fushun": "抚顺", "Changchun": "长春",
"Harbin": "哈尔滨", "Nanjing": "南京", "Suzhou": "苏州", "Wuxi": "无锡",
"Changzhou": "常州", "Nantong": "南通", "Yangzhou": "扬州", "Xuzhou": "徐州",
"Hangzhou": "杭州", "Ningbo": "宁波", "Wenzhou": "温州", "Jiaxing": "嘉兴",
"Hefei": "合肥", "Wuhu": "芜湖", "Bengbu": "蚌埠", "Fuzhou": "福州",
"Xiamen": "厦门", "Quanzhou": "泉州", "Nanchang": "南昌", "Ganzhou": "赣州",
"Jinan": "济南", "Qingdao": "青岛", "Yantai": "烟台", "Zhengzhou": "郑州",
"Luoyang": "洛阳", "Kaifeng": "开封", "Xinyang": "信阳", "Nanyang": "南阳",
"Zhumadian": "驻马店", "Wuhan": "武汉", "Huanggang": "黄冈", "Changsha": "长沙",
"Zhuzhou": "株洲", "Guangzhou": "广州", "Shenzhen": "深圳", "Dongguan": "东莞",
"Foshan": "佛山", "Zhuhai": "珠海", "Shantou": "汕头", "Yangjiang": "阳江",
"Nanning": "南宁", "Guilin": "桂林", "Haikou": "海口", "Sanya": "三亚",
"Chengdu": "成都", "Mianyang": "绵阳", "Guiyang": "贵阳", "Kunming": "昆明",
"Lhasa": "拉萨", "Xi'an": "西安", "Xianyang": "咸阳", "Lanzhou": "兰州",
"Xining": "西宁", "Yinchuan": "银川", "Urumqi": "乌鲁木齐", "Tokyo": "东京",
"Osaka": "大阪", "Seoul": "首尔", "Bangkok": "曼谷", "Singapore": "新加坡",
"New York": "纽约", "Los Angeles": "洛杉矶", "San Francisco": "旧金山",
"London": "伦敦", "Paris": "巴黎", "Berlin": "柏林", "Moscow": "莫斯科",
"Sydney": "悉尼", "Melbourne": "墨尔本", "Toronto": "多伦多"
};

const toChineseCity = (city) => cityNameMap[city] || city;

const directAdminMunicipalities = ["北京市", "天津市", "上海市", "重庆市"];

const formatLocation = (country, prov, city) => {
const cnCountry = toChineseCountry(country);
const cnProv = toChineseProvince(prov);
const cnCity = toChineseCity(city);
if (cnCountry === "中国") {
return directAdminMunicipalities.includes(cnProv) ? cnProv : `${cnProv} ${cnCity}`;
}
return cnCountry || '神秘地区';
};

const generateWelcomeMessage = (pos, dist, ipDisplay, country, prov, city) => `
<div class="welcome-content">
<div class="welcome-line welcome-location">✨ 欢迎来自 <b>${pos}</b> 的朋友</div>
<div class="welcome-line welcome-time">${getTimeGreeting()}</div>
<div class="welcome-line welcome-distance">📍 距博主约 <b>${dist}</b> 公里</div>
<div class="welcome-line welcome-greeting">💫 <b>${getGreeting(country, prov, city)}</b></div>
</div>
`;

const addStyles = () => {
const style = document.createElement('style');
style.textContent = `
#welcome-info {
user-select: none;
display: flex;
justify-content: center;
align-items: center;
min-height: 180px;
padding: 20px 16px;
margin-top: 8px;
border-radius: 14px;
background: linear-gradient(135deg, var(--anzhiyu-background) 0%, var(--anzhiyu-card-bg, var(--anzhiyu-background)) 100%);
outline: 1px solid var(--anzhiyu-card-border);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
transition: box-shadow 0.3s ease;
}
#welcome-info:hover {
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}
.welcome-content {
text-align: center;
line-height: 1.8;
font-size: 14px;
}
.welcome-line {
margin: 4px 0;
animation: fadeInUp 0.5s ease forwards;
opacity: 0;
}
.welcome-location {
animation-delay: 0.1s;
font-size: 16px;
white-space: nowrap;
}
.welcome-time {
animation-delay: 0.2s;
font-size: 15px;
}
.welcome-distance {
animation-delay: 0.3s;
font-size: 14px;
color: var(--anzhiyu-font-color, #666);
}
.welcome-greeting {
animation-delay: 0.4s;
font-size: 14px;
margin-top: 6px;
padding-top: 6px;
border-top: 1px dashed var(--anzhiyu-card-border);
color: var(--anzhiyu-main);
white-space: nowrap;
}
.welcome-line b {
color: var(--anzhiyu-main);
}
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(8px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.loading-spinner {
width: 40px;
height: 40px;
border: 3px solid rgba(0, 0, 0, 0.06);
border-radius: 50%;
border-top-color: var(--anzhiyu-main);
animation: spin 0.8s linear infinite;
}
@keyframes spin {
100% { transform: rotate(360deg); }
}
.error-message {
color: #ff6565;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 8px;
}
.error-message p,
.permission-dialog p {
margin: 0;
}
.error-icon {
font-size: 2.5rem;
}
#retry-button {
margin: 0 4px;
color: var(--anzhiyu-main);
cursor: pointer;
transition: transform 0.3s ease;
}
#retry-button:hover {
transform: rotate(180deg);
}
.permission-dialog {
text-align: center;
}
.permission-dialog button {
margin: 10px 6px;
padding: 8px 20px;
border: none;
border-radius: 20px;
background-color: var(--anzhiyu-main);
color: white;
font-size: 14px;
cursor: pointer;
transition: all 0.3s ease;
}
.permission-dialog button:hover {
transform: translateY(-2px);
opacity: 0.9;
}
.permission-dialog button[data-action="deny"] {
background-color: transparent;
color: var(--anzhiyu-font-color);
border: 1px solid var(--anzhiyu-card-border);
box-shadow: none;
}
.permission-dialog button[data-action="deny"]:hover {
background-color: var(--anzhiyu-background);
transform: translateY(-2px);
}
`;
document.head.appendChild(style);
};

// 位置权限相关函数
const checkLocationPermission = () => localStorage.getItem('locationPermission') === 'granted';
const saveLocationPermission = (permission) => {
localStorage.setItem('locationPermission', permission);
};
const showLocationPermissionDialog = () => {
const welcomeInfoElement = document.getElementById("welcome-info");
welcomeInfoElement.innerHTML = `
<div class="permission-dialog">
<div class="error-icon">❓</div>
<p>是否允许访问您的位置信息?</p>
<button data-action="allow">允许</button>
<button data-action="deny">拒绝</button>
</div>
`;

welcomeInfoElement.addEventListener('click', (e) => {
if (e.target.tagName === 'BUTTON') {
const action = e.target.dataset.action;
const permission = action === 'allow' ? 'granted' : 'denied';
handleLocationPermission(permission);
}
});
};
const handleLocationPermission = (permission) => {
saveLocationPermission(permission);
if (permission === 'granted') {
showLoadingSpinner();
fetchIpInfo();
} else {
showErrorMessage('您已拒绝访问位置信息');
}
};

const showLoadingSpinner = () => {
const welcomeInfoElement = document.querySelector("#welcome-info");
if (!welcomeInfoElement) return;
welcomeInfoElement.innerHTML = '<div class="loading-spinner"></div>';
};

const IP_CACHE_KEY = 'ip_info_cache';
const getIpInfoFromCache = () => {
const cached = localStorage.getItem(IP_CACHE_KEY);
if (!cached) return null;

const { data, timestamp } = JSON.parse(cached);
if (Date.now() - timestamp > IP_CONFIG.CACHE_DURATION) {
localStorage.removeItem(IP_CACHE_KEY);
return null;
}
return data;
};
const setIpInfoCache = (data) => {
localStorage.setItem(IP_CACHE_KEY, JSON.stringify({
data,
timestamp: Date.now()
}));
};

const fetchIpInfo = async () => {
if (!checkLocationPermission()) {
showLocationPermissionDialog();
return;
}

showLoadingSpinner();

const cachedData = getIpInfoFromCache();
if (cachedData) {
showWelcome(cachedData);
return;
}

try {
const data = await fetchIpData();
setIpInfoCache(data);
showWelcome(data);
} catch (error) {
console.error('获取IP信息失败:', error);
showErrorMessage();
}
};

const greetings = {
"中国": {
"北京市": "北——京——欢迎你~~~",
"天津市": "讲段相声吧",
"河北省": "山势巍巍成壁垒,天下雄关铁马金戈由此向,无限江山",
"山西省": "展开坐具长三尺,已占山河五百余",
"内蒙古自治区": "天苍苍,野茫茫,风吹草低见牛羊",
"辽宁省": "我想吃烤鸡架!",
"吉林省": "状元阁就是东北烧烤之王",
"黑龙江省": "很喜欢哈尔滨大剧院",
"上海市": "众所周知,中国只有两个城市",
"江苏省": {
"南京市": "这是我挺想去的城市啦",
"苏州市": "上有天堂,下有苏杭",
"其他": "散装是必须要散装的"
},
"浙江省": {
"杭州市": "东风渐绿西湖柳,雁已还人未南归",
"其他": "望海楼明照曙霞,护江堤白蹋晴沙"
},
"河南省": {
"郑州市": "豫州之域,天地之中",
"信阳市": "品信阳毛尖,悟人间芳华",
"南阳市": "臣本布衣,躬耕于南阳此南阳非彼南阳!",
"驻马店市": "峰峰有奇石,石石挟仙气嵖岈山的花很美哦!",
"开封市": "刚正不阿包青天",
"洛阳市": "洛阳牡丹甲天下",
"其他": "可否带我品尝河南烩面啦?"
},
"安徽省": "蚌埠住了,芜湖起飞",
"福建省": "井邑白云间,岩城远带山",
"江西省": "落霞与孤鹜齐飞,秋水共长天一色",
"山东省": "遥望齐州九点烟,一泓海水杯中泻",
"湖北省": {
"黄冈市": "红安将军县!辈出将才!",
"其他": "来碗热干面~"
},
"湖南省": "74751,长沙斯塔克",
"广东省": {
"广州市": "看小蛮腰,喝早茶了嘛~",
"深圳市": "今天你逛商场了嘛~",
"阳江市": "阳春合水!博主家乡~ 欢迎来玩~",
"其他": "来两斤福建人~"
},
"广西壮族自治区": "桂林山水甲天下",
"海南省": "朝观日出逐白浪,夕看云起收霞光",
"四川省": "康康川妹子",
"贵州省": "茅台,学生,再塞200",
"云南省": "玉龙飞舞云缠绕,万仞冰川直耸天",
"西藏自治区": "躺在茫茫草原上,仰望蓝天",
"陕西省": "来份臊子面加馍",
"甘肃省": "羌笛何须怨杨柳,春风不度玉门关",
"青海省": "牛肉干和老酸奶都好好吃",
"宁夏回族自治区": "大漠孤烟直,长河落日圆",
"新疆维吾尔自治区": "驼铃古道丝绸路,胡马犹闻唐汉风",
"台湾省": "我在这头,大陆在那头",
"香港特别行政区": "永定贼有残留地鬼嚎,迎击光非岁玉",
"澳门特别行政区": "性感荷官,在线发牌",
"其他": "带我去你的城市逛逛吧!"
},
"美国": "Let us live in peace!",
"日本": "よろしく、一緒に桜を見ませんか",
"俄罗斯": "干了这瓶伏特加!",
"法国": "C'est La Vie",
"德国": "Die Zeit verging im Fluge.",
"澳大利亚": "一起去大堡礁吧!",
"加拿大": "拾起一片枫叶赠予你",
"其他": "带我去你的国家逛逛吧"
};

const getGreeting = (country, province, city) => {
const cnCountry = toChineseCountry(country);
const cnProv = toChineseProvince(province);
const cnCity = toChineseCity(city);
const countryGreeting = greetings[cnCountry] || greetings["其他"];
if (typeof countryGreeting === 'string') {
return countryGreeting;
}
const provinceGreeting = countryGreeting[cnProv] || countryGreeting["其他"];
if (typeof provinceGreeting === 'string') {
return provinceGreeting;
}
return provinceGreeting[cnCity] || provinceGreeting["其他"] || countryGreeting["其他"];
};
const getTimeGreeting = () => {
const hour = new Date().getHours();
if (hour < 11) return "🌅 早上好,一日之计在于晨";
if (hour < 13) return "☀️ 中午好,记得午休喔~";
if (hour < 17) return "🍵 下午好,记得多喝水!";
if (hour < 19) return "🌇 即将下班,记得按时吃饭~";
return "🌙 晚上好,夜生活来咯!";
};

const showErrorMessage = (message = '抱歉,无法获取信息') => {
const welcomeInfoElement = document.getElementById("welcome-info");
welcomeInfoElement.innerHTML = `
<div class="error-message">
<div class="error-icon">😕</div>
<p>${message}</p>
<p>请<i id="retry-button" class="fa-solid fa-arrows-rotate"></i>重试或检查网络连接</p>
</div>
`;

document.getElementById('retry-button').addEventListener('click', fetchIpInfo);
};

const isHomePage = () => {
return window.location.pathname === '/' || window.location.pathname === '/index.html';
};

// 初始化
document.addEventListener('DOMContentLoaded', () => {
addStyles();
insertAnnouncementComponent();
document.addEventListener('pjax:complete', insertAnnouncementComponent);
});

修改配置

只需要修改一个地方:计算访客与博主距离时的经纬度坐标

1
2
3
4
5
6
7
8
9
window.IP_CONFIG = {
// API_KEY: '848dbcf5d47e39c6', // API密钥 申请地址:https://api.76.al/ 已失效
BLOG_LOCATION: {
lng: 121.4581, // 经度
lat: 31.2222 // 纬度
},
CACHE_DURATION: 1000 * 60 * 60, // 可配置缓存时间(默认1小时)
HOME_PAGE_ONLY: true, // 是否只在首页显示 开启后其它页面将不会显示这个容器
};

获取经纬度坐标

访问:https://ip-api.com/,获取 lat,lon

获取你的经纬度并替换

1
2
3
4
5
// 修改为你自己的经纬度  
BLOG_LOCATION: {
lng: 121.4581, // 经度
lat: 31.2222 // 纬度
},

引入自定义js

修改主题配置文件,引入自定义js

1
2
3
4
inject:
bottom:
# 自定义js
- <script src="/api/card-welcome.js"></script>

确认_config.anzhiyu.yml主题配置文件下aside配置项中的card_announcement是否开启,配置参考

1
2
3
4
5
6
7
card_announcement:
enable: true # 必须开启
content: <span>👋🏻 Hi,我是時光,欢迎您!</span><br>
<span>❓ 如有问题欢迎评论区交流!</span><br>
<span>😫 页面异常?尝试<kbd>Ctrl</kbd>+<kbd>F5</kbd></span><br>
<span>📧 如需联系我:<a href="mailto:[email protected]"><b>发送邮件🚀</b></a></span>
<div id="welcome-info"></div> # 必须项

方案二(已失效)

效果预览

image-20241025104832859

配置步骤

创建js文件

在主题目录下创建js文件,例如我存放的位置为:blog\themes\anzhiyu\source\js\custom\visitor.js

粘贴以下内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
const addStyles = () => {
const style = document.createElement('style');
style.textContent = `
#welcome-info {
display: flex;
justify-content: center;
align-items: center;
height: 192px;
}
.loading-spinner {
width: 50px;
height: 50px;
border: 3px solid rgba(0, 0, 0, 0.1);
border-radius: 50%;
border-top: 3px solid #3498db;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
`;
document.head.appendChild(style);
};

// 创建来访者卡片 在头像容器下方插入 位置更改自己找找元素
const createAnnouncementComponent = () => {
const ipInfoElement = document.createElement('div');
ipInfoElement.className = "card-widget card-ip-info";
ipInfoElement.innerHTML = `
<div class="item-headline">
✨✨ <span>轻轻的你来了 ✨✨</span>
</div>
<div class="announcement_content">
<div id="welcome-info">
<div class="loading-spinner"></div>
</div>
</div>
`;
return ipInfoElement;
};

// 插入组件
const insertAnnouncementComponent = () => {
if (!isHomePage()) return; // 只在首页插入

const cardInfo = document.querySelector('.card-widget.card-info');
if (cardInfo) {
const existingComponent = document.querySelector('.card-widget.card-ip-info');
if (existingComponent) {
existingComponent.remove();
}
cardInfo.parentNode.insertBefore(createAnnouncementComponent(), cardInfo.nextSibling);
}
};

// 获取 IP 信息
const fetchIpInfo = () => {
fetch('https://api.76.al/api/ip/query?key=your_key') //修改为自己都key
.then(response => response.ok ? response.json() : Promise.reject('网络响应不正常'))
.then(data => {
showWelcome(data);
})
.catch(error => {
console.error('错误:', error);
showErrorMessage();
});
};

// 距离计算函数
const getDistance = (e1, n1, e2, n2) => {
const R = 6371; // 地球半径
const { sin, cos, asin, PI, hypot } = Math;

const getPoint = (e, n) => {
e *= PI / 180;
n *= PI / 180;
return { x: cos(n) * cos(e), y: cos(n) * sin(e), z: sin(n) };
};

const a = getPoint(e1, n1);
const b = getPoint(e2, n2);
const c = hypot(a.x - b.x, a.y - b.y, a.z - b.z);
return Math.round(asin(c / 2) * 2 * R);
};

// 国家及省份的欢迎信息
const greetings = {
"中国": {
"北京市": "北——京——欢迎你~~~",
"天津市": "讲段相声吧",
"河北省": "山势巍巍成壁垒,天下雄关铁马金戈由此向,无限江山",
"山西省": "展开坐具长三尺,已占山河五百余",
"内蒙古自治区": "天苍苍,野茫茫,风吹草低见牛羊",
"辽宁省": "我想吃烤鸡架!",
"吉林省": "状元阁就是东北烧烤之王",
"黑龙江省": "很喜欢哈尔滨大剧院",
"上海市": "众所周知,中国只有两个城市",
"江苏省": {
"南京市": "这是我挺想去的城市啦",
"苏州市": "上有天堂,下有苏杭",
"default": "散装是必须要散装的"
},
"浙江省": {
"杭州市": "东风渐绿西湖柳,雁已还人未南归",
"default": "望海楼明照曙霞,护江堤白蹋晴沙"
},
"河南省": {
"郑州市": "豫州之域,天地之中",
"信阳市": "品信阳毛尖,悟人间芳华",
"南阳市": "臣本布衣,躬耕于南阳此南阳非彼南阳!",
"驻马店市": "峰峰有奇石,石石挟仙气嵖岈山的花很美哦!",
"开封市": "刚正不阿包青天",
"洛阳市": "洛阳牡丹甲天下",
"default": "可否带我品尝河南烩面啦?"
},
"安徽省": "蚌埠住了,芜湖起飞",
"福建省": "井邑白云间,岩城远带山",
"江西省": "落霞与孤鹜齐飞,秋水共长天一色",
"山东省": "遥望齐州九点烟,一泓海水杯中泻",
"湖北省": {
"黄冈市": "红安将军县!辈出将才!",
"default": "来碗热干面~"
},
"湖南省": "74751,长沙斯塔克",
"广东省": {
"广州市": "看小蛮腰,喝早茶了嘛~",
"深圳市": "今天消费了吗?~",
"阳江市": "阳春合水~ 欢迎来玩~",
"default": "来两斤福建人~"
},
"广西壮族自治区": "桂林山水甲天下",
"海南省": "朝观日出逐白浪,夕看云起收霞光",
"四川省": "康康川妹子",
"贵州省": "茅台,学生,再塞200",
"云南省": "玉龙飞舞云缠绕,万仞冰川直耸天",
"西藏自治区": "躺在茫茫草原上,仰望蓝天",
"陕西省": "来份臊子面加馍",
"甘肃省": "羌笛何须怨杨柳,春风不度玉门关",
"青海省": "牛肉干和老酸奶都好好吃",
"宁夏回族自治区": "大漠孤烟直,长河落日圆",
"新疆维吾尔自治区": "驼铃古道丝绸路,胡马犹闻唐汉风",
"台湾省": "我在这头,大陆在那头",
"香港特别行政区": "永定贼有残留地鬼嚎,迎击光非岁玉",
"澳门特别行政区": "性感荷官,在线发牌",
"default": "带我去你的城市逛逛吧!"
},
"美国": "Let us live in peace!",
"日本": "よろしく,一緒に桜を見ませんか",
"俄罗斯": "干了这瓶伏特加!",
"法国": "C'est La Vie",
"德国": "Die Zeit verging im Fluge.",
"澳大利亚": "一起去大堡礁吧!",
"加拿大": "拾起一片枫叶赠予你",
"default": "带我去你的国家逛逛吧"
};

// 获取欢迎信息
const getGreeting = (country, province, city) => {
const countryGreeting = greetings[country] || greetings.default;
if (typeof countryGreeting === 'object') {
return countryGreeting[province]?.[city] || countryGreeting[province] || countryGreeting.default;
}
return countryGreeting;
};

// 显示欢迎信息
const showWelcome = (ipLocationData) => {
if (!ipLocationData || !ipLocationData.data) {
return showErrorMessage();
}

// 修改为你自己的经纬度
const myLng = 121.38206; //经度
const myLat = 31.11325; //维度

const { lng, lat, country, prov, city, district } = ipLocationData.data;
const dist = getDistance(myLng, myLat, lng, lat);
const ip = ipLocationData.ip.includes(":") ? "<br>好复杂,咱看不懂~(ipv6)" : ipLocationData.ip;
const pos = country === "中国" ? `${prov} ${city} ${district}` : country;
const posdesc = getGreeting(country, prov, city);

const timeChange = (() => {
const hour = new Date().getHours();
if (hour < 11) return "🌤️ 早上好,一日之计在于晨";
if (hour < 13) return "☀️ 中午好,记得午休喔~";
if (hour < 17) return "🕞 下午好,记得多喝水!";
if (hour < 19) return "🚶‍♂️ 即将下班,记得按时吃饭~";
return "🌙 晚上好,夜生活来咯!";
})();

const welcomeInfoElement = document.getElementById("welcome-info");
welcomeInfoElement.style.display = 'block'; // 改回块级显示
welcomeInfoElement.style.height = 'auto';

// 📌 您的IP为: <b><span>${ip}</span></b><br>
welcomeInfoElement.innerHTML = `
${timeChange} <br>
💖 欢迎来自 <b><span style="color: var(--kouseki-ip-color);font-size: var(--kouseki-gl-size)">${pos}</span></b> 的朋友。<br>
📏 您距博主约 <b><span style="color: var(--kouseki-ip-color)">${dist}</span></b> 公里!<br>
🍂 <b><span>${posdesc}</span></b><br>
`;
};

// 显示错误信息
const showErrorMessage = () => {
const welcomeInfoElement = document.getElementById("welcome-info");
welcomeInfoElement.style.display = 'block';
welcomeInfoElement.innerHTML = `
<p>获取IP信息失败,请检查网络.</p>
`;
};

// 处理 PJAX 完成事件
const handlePjaxComplete = () => {
insertAnnouncementComponent(); // 重新插入组件
if (isHomePage()) fetchIpInfo();
};

// 判断是否是首页
const isHomePage = () => {
return window.location.pathname === '/' || window.location.pathname === '/index.html';
};

// 初始化
const initialize = () => {
addStyles(); // 添加CSS样式
insertAnnouncementComponent(); // 插入组件
if (isHomePage()) {
fetchIpInfo(); // 获取 IP 信息并显示欢迎信息
}
document.addEventListener("pjax:complete", handlePjaxComplete);
};

window.onload = initialize;

修改配置

需要修改两个地方:

  • 获取IP地址时接口所需的API_KEY
  • 计算访客与博主距离时的经纬度坐标

获取API_KEY

注册青桔API,到密钥管理申请API_KEY即可,目前我们使用到的API是完全免费且无次数限制的。

替换https://api.76.al/api/ip/query?key=your_key这部分内容中的API_KEY

获取经纬度坐标

调用 经纬度信息查询接口 获取你的经纬度并替换

1
2
3
// 修改为你自己的经纬度  
const myLng = 121.38206; //经度
const myLat = 31.11325; //维度

引入自定义js

修改主题配置文件,引入自定义js

1
2
3
4
inject:
bottom:
# 自定义js
- <script src="/js/custom/visitor.js"></script>