初踩坑JS加载与audio接口:点击头像开始/暂停背景音乐


背景

封楼期间难得空闲,也静不下心学习,空闲之余萌生了重做引导单页的想法。因为之前都是扒站(某大公司游戏官网)+小改,一来虽然很炫酷,但本人水平有限,仍有很大一部分JS无从下手,甚至是看不懂|-_-|;二来对方毕竟没有开源,无论道德还是法律都说不过去,所以……先从简单处写起,后续慢慢迭代吧!

大致布局:Flex

参见 阮一峰Flex布局教程

头像部分

手残党,暂时没有用CSS或者JS绘制特效,因为之前做头像留着底图,所以偷个懒。
CSS:鼠标指针指向头像切换gif,移开切换png。
JS:音乐播放切换gif,暂停切换png。

背景音乐部分

audio接口参见 HTML audio基础API完全使用指南
我只循环播放了一首歌,所以隐藏audio主体美观一些,然后控制按钮交给头像。有需要多首歌的,可以看一下开源的APlayer

遇到的问题:JS加载阻塞,获取不到元素id

在实现头像处鼠标事件时,一直获取不到头像的id,但是控制台调试发现代码无误。原来由于JS的机制是单线程,所以先运行JS代码,再构建相关DOM,需要在外部引用JS时加上属性async,等构建完DOM再获取。


代码部分

HTML部分





    
    
    
    你听|睿屿青衫
    
    
    
    
    
    



    
头像/音乐控件

睿屿青衫

不惦来路,轻装且行

CSS部分

html,
body {
    height: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
}

body {
    background-image: linear-gradient(to right, #ec6fa3, #2f4af2);
}

.box {
    position: fixed;
    height: 100%;
    width: 100%;
    /* box铺满屏幕,需要html和body取消边距 */
    display: flex;
    align-items: center;
    justify-content: center;
    /* 盒子内部水平垂直居中对齐 */
}

.about {
    width: 70%;
    max-width: 750px;
    background-color: rgba(219, 245, 245, 0.1);
    padding: 1%;
}

#ava {
    display: block;
    width: 100px;
    height: 100px;
    border: 2px solid #1eccef;
    margin: auto;
    margin-top: 3%;
    border-radius: 100px;
}

#ava:hover {
    content: url("https://images.reashal.com/resources/avator/dyAva.gif");
}

#reashal {
    color: rgb(255, 255, 255);
    text-align: center;
    margin: auto;
}

.fgx {
    height: 1px;
    background-color: white;
}

ul,
li {
    display: inline-block;
    list-style: none;
    padding: 1vh;
    margin: auto;
}

i:hover {
    color: #ec6fa3;
}

.footer {
    bottom: 3%;
    width: 100%;
    position: fixed;
    text-align: center;
}

a,
p {
    color: white;
    font-size: 16px;
    text-decoration: none;
}

#music {
    display: none;
}

JS部分

音乐部分

var x = document.getElementById('ava');
// 单击头像开始/暂停背景音乐
var music = document.getElementById('music');
x.onclick = function () {
  if (music.paused) {
    music.play();
  }
  else {
    music.pause();
  }
}
//播放音乐旋转头像
music.onplay = function () {
  x.src = 'https://images.reashal.com/resources/avator/dyAva.gif';
  x.title = '点击暂停背景音乐';
}
//暂停音乐停止旋转头像
music.onpause = function () {
  x.src = 'https://images.reashal.com/resources/avator/reashal.png';
  x.title = '点击开启背景音乐';
}

点击特效部分

不贴了,想要的自己从我这里下载,别人写的我也看不懂……

暂时完工

后续 想起什么 学会点新东西再加
成品展示 以后慢慢 更新 吧