欢迎点击「算法与编程之美」↑关注我们!
本文首发于微信公众号:"算法与编程之美",欢迎关注,及时了解更多此系列文章。
欢迎加入团队圈子!与作者面对面!直接点击!
目录
问题描述
解决方案
在移动端实现页面亮度的调节,只需要移动滑动条即可轻易调亮调暗页面,那么在html网页中,要如何实现利用滑动条来调节亮度呢?
效果图:
图1 颜色改变效果
1 HTML
首先在html中将滑动条样式涉及的各项元素都呈现出来。
html代码如下:
<body>
<div></div>
<div></div>
<div style="border-bottom:3px solid #505151;" id="control_bar_mask"></div>
<div></div>
</body>
2 CSS
由于要使背景从黑到白,这里先为最外面的div mask添加一个全黑的background,后续只需要设置透明度即可实现;z-index是一个遮罩效果,值大的在上面,值小的就会被覆盖,这里的z-index:-1是让一个层在所有层的下面,相当于用其覆盖原来的背景。
control_bar用来设置滑动条的样式,control_bar_cursor用来设置滑动条上的游标,这里的cursor属性可以设置光标移动到游标上的效果。
CSS代码如下:
<style>
.mask{
position: fixed;
bottom: 0;
top: 0;
left: 0;
right: 0;
background: #000000;
z-index: -1;
}
.control_bar{
height: 200px;
width: 500px;
border-bottom: 3px solid #888888;
}
.control_bar_cursor{
height: 25px;
width: 8px;
background: #505151;
border-radius: 5px;
margin-top: -12.5px;
position: relative;
top:0;
left:0;
}
.control_bar_cursor:hover{
background: white;
}
#control_bar_mask{
margin-top: -203px;
width: 0px;
}
</style>
3 JS
先定义变量,获取div中的元素;通过clientX、clientY事件属性返回当事件被触发时鼠标指针向对于浏览器页面的水平和垂直坐标;然后利用if语句来实现游标的移动;再定义一个proportion变量,通过改变opacity属性值来设置透明度实现由黑到白的改变。
JS代码如下:
<script>
window.onload = function(){
var control_bar = document.getElementsByClassName("control_bar")[0];
var control_bar_mask = document.getElementById("control_bar_mask");
var control_bar_cursor = document.getElementsByClassName("control_bar_cursor")[0];
var def_left = control_bar_cursor.offsetLeft;
var mask = document.getElementsByClassName("mask")[0];
document.body.onmousedown = function(){
window.onmousemove = function(){
var cursor_X = event.clientX;
var cursor_Y = event.clientY;
if(cursor_X < def_left){
control_bar_cursor.style.left = 0;
}else if(cursor_X > control_bar.offsetWidth + def_left){
control_bar_cursor.style.left = control_bar.offsetWidth;
}else{
control_bar_cursor.style.left = cursor_X - def_left + "px";
}
//亮度比
var proportion = parseInt(control_bar_cursor.offsetLeft - def_left) / parseInt(control_bar.offsetWidth - 1);
control_bar_mask.style.width = proportion * control_bar.offsetWidth + "px";
mask.style.opacity = 1 - proportion;
};
window.onmouseup = function(){
window.onmousemove = null;
};
};
};
</script>
END
主 编 | 王楠岚
责 编 | wrape
能力越强,责任越大。实事求是,严谨细致。
——where2go 团队
微信号:算法与编程之美
长按识别二维码关注我们!
温馨提示:点击页面右下角“写留言”发表评论,期待您的参与!期待您的转发!