祖传代码

2023-07-30 17:24:47 浏览数 (1)

网页字体大小自适应

用rem定义元素元素的大小,实现根据屏幕缩放控制大小。

代码语言:javascript复制
/*控制rem*/
let c = () =>{
    let width = document.documentElement.clientWidth;
    let height = document.documentElement.clientHeight;
    adapt(width, height);
}
window.addEventListener("load", c);
window.addEventListener("resize", c);

/*rem调整*/
function adapt(w, h) {
    let html = document.documentElement;
    /*根据宽高比调整*/
    html.style.fontSize = ((w*h)/20000)**0.5   'px';
    /*
    根据宽调整
    html.style.fontSize = w / 200   'px'
    */
    /*
    根据高调整
    html.style.fontSize = h / 200   'px'
    */
}
主题切换功能

设置两个样式表dark.css和light.css,link标签id为theme,单击按钮改变href值,并切换图标。

代码语言:javascript复制
/*页面第一次加载时根据时间确定主题*/
window.onload = time;

/*主题随时间*/
function time(){
    let data = new Date();
    let hour = data.getHours();
    let theme = document.getElementById('theme')
    /*太阳或月亮的图标*/
    let img = document.getElementById("index").getElementsByTagName('img')[1];
    /*6点到18点为日间模式*/
    if (6<=Number(hour)&&Number(hour)<18){
        /*light模式*/
        img.id = "sun";
        img.src = "sun.png";
        theme.href = "light.css";
    }
    else {
        /*dark模式*/
        img.id = "moon";
        img.src = "moon.png";
        theme.href = "dark.css";
    }
}
/*主题切换*/
function theme(){
    let theme = document.getElementById('theme');

    /*切换到dark模式*/
    if (document.getElementById("sun")){
        let sun = document.getElementById("sun");
        sun.id = "moon";
        sun.src = "moon.png";
        theme.href = "dark.css";

    }
    /*切换到light模式*/
    else if (document.getElementById("moon")){
        let moon = document.getElementById("moon");
        moon.id = "sun";
        moon.src = "sun.png";
        theme.href = "light.css";
    }
    else {}
}

0 人点赞