让你的博客支持LivePhoto照片

一、效果预览

▲ LivePhoto 照片展示

二、添加JS脚本

   在主题js目录下(如我的是themes\anzhiyu\source\js)新建一个livephoto.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
(function() {
// 当文档加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
// 查找所有带有live-photo类的元素
var livePhotoElements = document.querySelectorAll('.live-photo');

if (livePhotoElements.length > 0) {
// 如果页面上有实况照片元素,才加载LivePhotosKit.js
var script = document.createElement('script');
script.src = 'https://cdn.apple-livephotoskit.com/lpk/1/livephotoskit.js';
script.onload = function() {
// LivePhotosKit.js加载完成后,初始化所有实况照片
initializeLivePhotos(livePhotoElements);
};
document.head.appendChild(script);
}
});

// 初始化所有实况照片元素
function initializeLivePhotos(elements) {
elements.forEach(function(element) {
// 获取照片和视频的URL
var photoSrc = element.getAttribute('data-photo-src');
var videoSrc = element.getAttribute('data-video-src');

if (photoSrc && videoSrc) {
// 创建LivePhotosKit播放器
var player = LivePhotosKit.Player(element);

// 设置照片和视频源
player.photoSrc = photoSrc;
player.videoSrc = videoSrc;

// 添加鼠标悬停事件来播放实况照片
element.addEventListener('mouseenter', function() {
player.play();
});

element.addEventListener('mouseleave', function() {
player.pause();
});

// 添加触摸事件支持(移动设备)
element.addEventListener('touchstart', function() {
player.play();
});

element.addEventListener('touchend', function() {
player.pause();
});

// 添加样式
element.style.position = 'relative';
element.style.overflow = 'hidden';
element.style.display = 'inline-block';
}
});
}
})();

三、添加CSS样式

   在主题css目录(如我的是themes\anzhiyu\source\css)下新建一个livephoto.css文件,添加以下代码:

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
.livephoto {
display: grid;
place-items: center;
margin: 0;
padding: 0;
}

.live-photo {
display: grid;
place-items: center;
width: 100%;
max-width: 800px;
height: auto;
aspect-ratio: 4/3;
margin: 20px 0;
border-radius: 8px;
cursor: pointer;
}

.live-photo img {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 8px;
}

.live-photo video {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 8px;
}

四、引入js和css文件

   在主题配置文件_config.yml中,找到inject选项,在headbottom选项下,分别添加以下代码:

1
2
3
4
5
6
7
8
inject:
head:

# Livephoto
- <link rel="stylesheet" href="/css/livephoto.css">
bottom:
# Livephoto
- <script src="/js/livephoto.js"></script>

五、一键三连

   到这里,你已经成功添加了LivePhoto支持,接下来你只需要在你的博文里添加如下代码即可达到效果。

1
2
3
4
<div class="livephoto">
<div class="live-photo" data-photo-src="https://images.chn.us.kg/hexo/post/019-post-01.webp" data-video-src="https://images.chn.us.kg/hexo/post/019-post-01.mov">
</div>
</div>

注意事项:

  1. LivePhoto照片的URL请替换为你自己的照片和视频的URL。(视频格式好像需要是.mov,我用.mp4的视频显示不来,其他格式没试过);
  2. 实况照片的动态视频,iPhone手机可用将实况图片的视频直接保存,格式就是.mov的。
  3. hexo一键三连hexo clean && hexo g && hexo s,确保所有文件都生成后,你的博客就支持LivePhoto照片了。