我想在我的页面中制作一个微调控件,我尝试了这样的操作:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Simple spinner</title>
<script type="text/javascript">
function RotateSpinner(spinnerId, up) {
var ele=document.getElementById(spinnerId);
ele.value=parseInt(ele.value)+up;
var t=setTimeout(function(){
if(window.rotate_start)
RotateSpinner(spinnerId,up);
else
clearTimeout(t);
},500);
}
</script>
<style>
*
{
padding: 0;
margin: 0;
}
.spinner
{
list-style: none;
display: inline-block;
line-height: 0;
vertical-align: middle;
}
.spinner input
{
font-size: .45em;
border-width: .5px;
height: 1.5em;
width: 2em;
}
</style>
</head>
<body>
<input id="spinner" type="text" value="0" />
<ul class="spinner">
<li>
<input type="button" value="▲" onmousedown="window.rotate_start=true;RotateSpinner('spinner', 1)" onmouseup="window.rotate_start=false;"/>
</li>
<li>
<input type="button" value="▼" onmousedown="window.rotate_start=true;RotateSpinner('spinner', -1)" onmouseup="window.rotate_start=false;"/>
</li>
</ul>
</body>
</html>
但是,它并没有按照我想要的方式工作,当我单击“向上”按钮时,我希望该值只添加一次,但有时它会多次添加该值。
有人可以检查并修复它吗?
最佳答案
使用间隔可以大大缩短和简化代码。 (在 IE9、Chrome21、FF14 上测试) 我用过http://jsfiddle.net/KmMCE/3/用于测试,但我还没有更新示例。
标记:
<input id="spinner" type="text" value="0" />
<input type="button" value="▲"
onmousedown="spinnerMouseDown('spinner', 1);"
onmouseup="stopSpinner();" onmouseout="stopSpinner();" />
<input type="button" value="▼"
onmousedown="spinnerMouseDown('spinner', -1);"
onmouseup="stopSpinner();" onmouseout="stopSpinner();" />
JavaScript:
function spinnerMouseDown(id, value) {
var el = document.getElementById(id);
window.spinnerTimer = window.setInterval(function(){
el.value = parseInt(el.value) + value;
}, 100);
}
function stopSpinner() {
window.clearInterval(window.spinnerTimer);
}
关于javascript - 使用 javascript 在 html 页面中构建微调控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7995156/