<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>testView</title>
<style>
#box{
position: relative;
width: 200px;
height: 50px;
border: 1px solid #eee;
margin: 50px auto 0;
}
#bg{
height: 10px;
margin-top: 19px;
border: 1px solid #ddd;
border-radius: 5px;
overflow: hidden;
}
#bgcolor{
background: #5889B2;
width: 0; height: 10px;
border-radius: 5px;
}
#bt{
width: 15px; height: 15px;
background-color: red;
border-radius: 25px;
overflow: hidden;
position: absolute;
left: 0px;
margin-left: -10px;
top: 18px;
cursor: pointer;
}
#text{
width: 200px;
margin: 0 auto;
font-size: 16px;
line-height: 2em;
}
</style>
<script type="text/javascript" src="js/jquery-1.11.3.min.js" ></script>
</head>
<body>
<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依賴 jQuery,所以必須放在前邊) -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
<div id="box">
<div id="bg">
<div id="bgcolor"></div>
</div>
<div id="bt"></div>
</div>
<div id="text"></div>
<script type="text/javascript">
(function($){
var $box = $('#box');
var $bg = $('#bg');
var $bgcolor = $('#bgcolor');
var $btn = $('#bt');
var $text = $('#text');
var statu = false;
var ox = 0;
var lx = 0;
var left = 0;
var bgleft = 0;
$btn.mousedown(function(e){
lx = $btn.offset().left;
ox = e.pageX - left;
statu = true;
});
$(document).mouseup(function(){
statu = false;
});
$box.mousemove(function(e){
if(statu){
left = e.pageX - ox;
if(left < 0){
left = 0;
}
if(left > 200){
left = 200;
}
$btn.css('left',left);
$bgcolor.width(left);
$text.html('電壓:' + parseInt(left/2) + 'V');
}
});
$bg.click(function(e){
if(!statu){
bgleft = $bg.offset().left;
left = e.pageX - bgleft;
if(left < 0){
left = 0;
}
if(left > 200){
left = 200;
}
$btn.css('left',left);
$bgcolor.stop().animate({width:left},200);
$text.html('電壓:' + parseInt(left/2) + 'V');
}
});
})(jQuery);
</script>
</body>
</html>
結果: