audio对象属性: volume 描述:设置或返回音频的音量,取值范围(0——1)
下面是我做的音乐播放器如何调节音频音量的代码:
//增加切换音量事件
(function(){
var height = $("#myaudio ul.control li.volume .alert-box .volume-wrap .bar .scroll-bar").height();
$("#myaudio ul.control li.volume .alert-box .volume-wrap .bar .scroll-bar .scroll-btn").on("mousedown",function(e){
e.preventdefault();
var downheight = $("#myaudio ul.control li.volume .alert-box .volume-wrap .bar .scroll-bar").height();
var downy = e.clienty;
document.onmousemove = function(e){
e.preventdefault();
var movey = e.clienty;
var nowheight = downy-movey+downheight;
if(nowheight<=0){
nowheight =0;
}else if(nowheight >= height){
nowheight = height;
}
$("#myaudio ul.control li.volume .alert-box .volume-wrap .bar .scroll-bar").height(nowheight);
var precent = nowheight/height;
audio.volume = precent;
}
document.onmouseup = function(){
document.onmousemove = null;
document.onmouseup = null;
}
});
})();
上面的主要思路:声明height变量先获取调节音量的滑动条的高度(设置的是80px),
给滑动条上的滑动块绑定mousedown事件,取消其默认事件e.preventdefault();
声明downheight获取未滑动时的音量滑动条的高度, 声明downy获取点击位置距离窗口上方的y(垂直)方向距离var downy = e.clienty;
给整个dom添加mousemove事件,取消其默认事件e.preventdefault();
声明movey获取光标移动到的位置距离窗口上方的y(垂直)方向距离var movey = e.clienty;
声明nowheight获取调节后音量滑动条的高度var nowheight = downy-movey+downheight;
因为滑动条的高度为80px,所以在下面判断了一下
if(nowheight <=0){
nowheight=0;//最小值为0(对应volume静音)
}else if(nowheight>=height){
nowheight=height;//最大值为80px(对应volume最大值1)
}
将调节后的音量条高度赋值给滑动条,实现调节时滑动条同步变换高度;
由于音量vojume的取值范围(0-1),让nowheight/height 得到调节后高度对总体高度的百分比,值为(0-1)
最后将这个值赋予audio.volume=nowheight/height;
当调节结束后,松开鼠标添加mouseup事件,将mousemove和mouseup事件都清空
以上就是html5中关于volume属性的使用详解的详细内容。