2023-08-05  2024-09-18    442 字  1 分钟

当页面失去焦点时改变标题,恢复焦点时恢复标题

将js文件放在主题的static/js文件夹中

在layouts/partials/head.html中添加

1    {{ if .Site.Params.funnyTitle | default false }}
2    <script src="/js/funny_title.js"></script>
3    {{- end -}}

此时在hugo.toml中添加以下内容开启

1[params]
2    # 动态标题
3    funnyTitle = true

funny_title.js

 1( function (global) {
 2	var vendorPrefix=getBrowserPrefix();
 3	var eventName=visibilityEvent(vendorPrefix);
 4	document.addEventListener(eventName,visibilityEventCallback);
 5
 6	var titleTime;
 7	var oldTitle=document.title;
 8	function visibilityEventCallback(){
 9		if(document.hidden){
10
11			document.title="╭(°A°`)╮ 页面崩溃啦 ~ 快回来看看~ | "+oldTitle;
12            clearTimeout(titleTime);
13		}else{
14			document.title="(ฅ>ω<*ฅ) 噫又好了~";
15            titleTime = setTimeout(function() {
16                document.title = oldTitle;
17            }, 2000);
18		}
19	}
20// Get Browser-Specifc Prefix
21	function getBrowserPrefix() {
22	
23	  	// Check for the unprefixed property.  
24	  	if ('hidden' in document) {
25	    	return null;
26		}
27	
28		// All the possible prefixes.  
29		var browserPrefixes = ['moz', 'ms', 'o', 'webkit'];
30		 
31		for (var i = 0; i < browserPrefixes.length; i++) {
32		    var prefix = browserPrefixes[i] + 'Hidden';
33		    if (prefix in document) {
34		      return browserPrefixes[i];
35		    }  
36		}
37	
38	 	// The API is not supported in browser.  
39	 	return null;
40	}
41	
42	// Get Browser Specific Hidden Property
43	function hiddenProperty(prefix) {
44		if (prefix) {
45			return prefix + 'Hidden';
46		} else {
47			return 'hidden';
48		}
49	}
50	
51	// Get Browser Specific Visibility State
52	function visibilityState(prefix) {
53	  if (prefix) {
54	    return prefix + 'VisibilityState';
55	  } else {
56	    return 'visibilityState';
57	  }
58	}
59	
60	// Get Browser Specific Event
61	function visibilityEvent(prefix) {
62	  if (prefix) {
63	    return prefix + 'visibilitychange';
64	  } else {
65	    return 'visibilitychange';
66	  }
67	}
68})(this);

除另有声明外本博客文章均采用 知识共享 (Creative Commons) 署名 4.0 国际许可协议 进行许可转载请注明原作者与文章出处