javascript - 使用 javascript 在 html 页面中构建微调控件

标签 javascript spinner

我想在我的页面中制作一个微调控件,我尝试了这样的操作:

<!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="&#9650;" onmousedown="window.rotate_start=true;RotateSpinner('spinner', 1)" onmouseup="window.rotate_start=false;"/>
        </li>
        <li>
            <input type="button" value="&#9660;" onmousedown="window.rotate_start=true;RotateSpinner('spinner', -1)" onmouseup="window.rotate_start=false;"/>
        </li>
    </ul>
</body>
</html>

但是,它并没有按照我想要的方式工作,当我单击“向上”按钮时,我希望该值只添加一次,但有时它会多次添加该值。

有人可以检查并修复它吗?

这是live example

最佳答案

使用间隔可以大大缩短和简化代码。 (在 IE9、Chrome21、FF14 上测试) 我用过http://jsfiddle.net/KmMCE/3/用于测试,但我还没有更新示例。

标记:

    <input id="spinner" type="text" value="0" />
    <input type="button" value="&#9650;"
      onmousedown="spinnerMouseDown('spinner', 1);" 
onmouseup="stopSpinner();" onmouseout="stopSpinner();" />

    <input type="button" value="&#9660;"
      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/

相关文章:

listview - 如何通过 ListView 进行过滤

php - 无法将 JSON 数据正确加载到 Spinner 中

android - 如何以编程方式将字体自定义字体设置为 Spinner 文本?

html - CSS3 微调圆圈旋转

java - Android Spinner 未显示

javascript - IE11 访问被拒绝错误

javascript - 使用 jQuery 的 ajax 方法将图像检索为 blob

javascript - React Native 中的文本位置

Javascript href 在页面上留下 url

javascript - 如何使用文本而不是每列过滤整个表格 ng-grid 3.0 (ui-grid)