技术栈教程让你的博客支持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() { var livePhotoElements = document.querySelectorAll('.live-photo');
if (livePhotoElements.length > 0) { var script = document.createElement('script'); script.src = 'https://cdn.apple-livephotoskit.com/lpk/1/livephotoskit.js'; script.onload = function() { initializeLivePhotos(livePhotoElements); }; document.head.appendChild(script); } });
function initializeLivePhotos(elements) { elements.forEach(function(element) { var photoSrc = element.getAttribute('data-photo-src'); var videoSrc = element.getAttribute('data-video-src');
if (photoSrc && videoSrc) { 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
选项,在head
和bottom
选项下,分别添加以下代码:
1 2 3 4 5 6 7 8
| inject: head:
- <link rel="stylesheet" href="/css/livephoto.css"> bottom: - <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>
|
注意事项:
- LivePhoto照片的URL请替换为你自己的照片和视频的URL。(视频格式好像需要是.mov,我用.mp4的视频显示不来,其他格式没试过);
- 实况照片的动态视频,iPhone手机可用将实况图片的视频直接保存,格式就是.mov的。
- hexo一键三连
hexo clean && hexo g && hexo s
,确保所有文件都生成后,你的博客就支持LivePhoto照片了。