点击拖拽目标可以进行左右拖拽,鼠标抬起停止拖拽,边界处理,评分进度和分数同时改变,分数保留一位小数
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>拖拽评分</title>
<style>
#test{
width: 600px;
height: 300px;
margin: 50px auto;
padding-top: 50px;
font-size: 12px;
}
#left,#right {
width: 20px;
height: 20px;
line-height: 20px;
float: left;
text-align: center;
}
#score{
width: 20px;
height: 20px;
line-height: 20px;
float: left;
margin-right: 10px;
text-align: center;
border: 1px solid #0f0;
}
#box{
float: left;
width: 400px;
height: 20px;
border: 1px solid #ccc;
border-radius: 10px;
margin: 0 10px;
position: relative;
}
#box #dp{
width: 0;
height: 100%;
border: 1px solid #0f0;
border-radius: 10px 0 0 10px;
background-color: #0f0;
}
#box #dra{
height: 30px;
width: 10px;
background-color: #0f0;
border-radius: 10px;
position: absolute;
top: -5px;
}
</style>
<script>
window.onload = function () {
var dra = document.getElementById('dra');
// var box = document.getElementById('box');
var dp = document.getElementById('dp');
var score = document.getElementById('score');
// 按下鼠标拖拽
dra.onmousedown = function (event) {
event = event || window.event;
var x = event.clientX - dra.offsetLeft;
// 移动鼠标获取坐标
document.onmousemove = function (event) {
event = event || window.event;
dra.style.left = event.clientX - x + 'px';
dp.style.width = event.clientX - x + 'px';
var s = 5*(event.clientX - x)/390; // 等比例换算
// 边界处理
if (event.clientX - x<=0) {
dra.style.left = '0';
s = 0;
}
if (event.clientX - x>=390) {
dra.style.left = '390px';
dp.style.width = '390px';
s = 5;
}
score.innerHTML = s.toFixed(1); // 评分保留一位小数
};
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
};
return false;
}
};
</script>
</head>
<body>
<div id="test">
<div id="score">0.0</div>
<div id="left">0</div>
<div id="box">
<div id="dp">
<div id="dra"></div>
</div>
</div>
<div id="right">5.0</div>
</div>
</body>
</html>