js文件
var objFun = {
bindEvent(boxID){
this.wrapperDom = document.getElementById(boxID);
this.audio = this.wrapperDom.querySelector('audio');
this.moon = this.wrapperDom.querySelector('.moon');
this.sun = this.wrapperDom.querySelector('.sun');
this.perinfo = this.wrapperDom.querySelector('.per');
var flag = false;
var dis;
//鼠标拖拽事件
this.moon.onmousedown = function (e) {
flag = true;
// 计算出鼠标落下点与月亮边界的距离
dis = e.clientX - this.moon.offsetLeft;
}.bind(this);
this.wrapperDom.onmousemove = function (e) {
if (!flag) {
return;
};
// 根据拖拽距离设置当前拖拽元素的位置
this.moon.style.left = (e.clientX - dis) + 'px';
// 调用控制音量的函数
this.getVoice();
}.bind(this);
// 鼠标抬起 结束拖拽事件
this.wrapperDom.onmouseup = function () {
flag = false;
}
},
getVoice(){
//太阳的宽度
var sunW = this.sun.clientWidth;
sunWL = this.sun.offsetLeft,
moonWL = this.moon.offsetLeft;
//月亮与太阳之间的距离
var distance = Math.abs(sunWL-moonWL)/sunW;
// 0 - 1
this.changeVoice(distance);
},
changeVoice(vol){
if(vol>=1){
this.audio.pause()
return;
}
this.audio.play();
// 根据百分比设置音量
this.audio.volume = 1-vol;
// 填充html内容
var str = "Volume: " + (1-vol);
this.perinfo.innerHTML = str;
// 设置背景颜色值
this.moon.style.background = `rgba(${vol}34,12,67,1)`
this.wrapperDom.style.background=`rgba(${vol},53,15,1)`;
}
}
html
日食音量调节拖动地球远近来控制音乐播放~调节声音大小~
objFun.bindEvent('wrapperDom');
福建小徐
发布了188 篇原创文章 · 获赞 154 · 访问量 1万+
私信
关注
标签:audio,vol,sun,调节器,moon,wrapperDom,音量,var,JS
来源: /weixin_41181778/article/details/104058863