Hexo的matery主题设置移动端背景图
前言
搭建好Hexo的博客后,且用的是matery主题。当我们使用手机或其它移动端访问博客时,发现,呀!这背景图好大啊,一点也不美观。
所以我们可以检测设备是否为移动端,若是移动端,则更换指定图片
准备
首先,你需要准备几张手机竖屏背景图,最好像素高一些(因为有些平板也会被检测为移动端)
然后将图片扔到你主题的source/medias/images
目录下即可
然后记得将图片从1开始递增排序
修改代码
打开主题目录下的source/js/matery.js
文件,将以下内容添加到$(function () {})
中
/**
* uri检测
* PC移动端检测
*/
// console.log(window.location.pathname);
if (window.location.pathname === "/") {
if (navigator.userAgent.match(/mobile/i)) {
// alert("移动端");
// 获取网页可见宽高
const moveWidth = document.documentElement.clientWidth
const moveHeight = document.documentElement.clientHeight
const moveResult = moveWidth / moveHeight
// console.log(moveWidth + "\t" + moveHeight);
// console.log(moveResult);
if (moveResult <= 0.65) {
// 竖屏手机
// 移动端背景图总个数
const bgnum = 20;
// 第几张图
const bg = parseInt(Math.random() * bgnum) + 1
// alert("num:" + bg)
$(".bg-cover").css("background-image", `url(medias/images/${bg}.jpeg)`)
}
}
// else{
// // alert("pc端");
// }
}
代码解析
window.location.pathname
用来获取uri,就算uri中有#也不用怕,还是删掉#的路径,这样就少了一个判断document.documentElement.clientWidth
和document.documentElement.clientHeight
分别来获取浏览器网页可见的宽高moveResult <= 0.65
是宽高比小于0.65的就视为正常使用手机,否则就是横屏使用手机或平板parseInt(Math.random()*bgnum)
是用来获取0~你指定图片个数的随机数值-1,因为我是从1开始的,所以后面直接+1,若你的图片是从0开始的则不用管
易错提醒
- 一定要记得将你的图片名更改为1开始的数字递增
- 修改上面代码的移动背景图的总个数,为你图片的个数
- 检查图片后缀名是否为jpeg,若不是,修改上面代码的后缀为你图片的后缀即可