增加屏幕上显示的数值



我需要有一个数字,显示在一个网页上,将增加或减少当向上或向下箭头键被按下。我发现/一起按摩javascript文件做到这一点,但我似乎不能让它与我的HTML工作。我试图链接到一个html文本框,但它不会工作。

如果有人能帮我用HTML让这个工作,那将是伟大的。

var setTimeoutId; 
var keyIs = "up"; 
 function myIncrementFunction()
{
        var num = parseFloat(myText.value)+1;
        myText.value = num; 
}
myText.onkeydown = function(e)
{
keyIs = "down";
if(keyIs == "down")
    {
        var e = e || event ;
        if (e.keyCode == 38)
            {    
                for(var s=0; s<1; s++)
                    setTimeoutId = setTimeout('myIncrementFunction()',100); 
            }
    }
}
myText.onkeyup = function(e)
{ 
 keyIs = "up"; 
}

尝试了这个,它仍然不工作。>吗?

number.html

<html>
<head>
<script type="text/javascript" src="number.js"></script>
</head>
<body>
<input type="text" id="myText" />
</body>
</html>

number.js

var myText = document.getElementById("myText");
// Capture keyDown events
myText.onkeydown = function(e) {
// "38" is the up arrow key
if (e.keyCode == 38) {
    // increment the value in the text input
    myText.value++;
// "40" is the down arrow key
} else if (e.keyCode == 40) {
    // decrement the value in the text input
    myText.value--;
}
}

我不明白为什么它在张贴的例子中工作,当我保存我的文件并在浏览器中打开它时,它将不起作用!

我在OSX Lion上使用Chrome/Safari

看起来有几件事正在发生。首先,正如jayp在他的评论中指出的,你没有定义什么是myText

其次,我认为你把事情弄得太复杂了。不如这样试试:

给你的文本输入一个ID,比如<input type="text" id="myText" />

然后像这样写:

// Assign our text input to a variable
var myText = document.getElementById("myText");
// Capture keyDown events
myText.onkeydown = function(e) {
    // "38" is the up arrow key
    if (e.keyCode == 38) {
        // increment the value in the text input
        myText.value++;
    // "40" is the down arrow key
    } else if (e.keyCode == 40) {
        // decrement the value in the text input
        myText.value--;
    }
}

这是一个非常简单的例子,但应该能让你找到正确的方向。希望能有所帮助。

查看JSFiddle

中的工作示例编辑:

在您的情况下不起作用,因为脚本试图在页面完全加载之前找到input元素。您可以像这样将脚本移动到页面底部:

<html>
    <head></head>
    <body>
        <input type="text" id="myText" />
        <script type="text/javascript" src="number.js"></script>
    </body>
</html>

在您的number.js中,您正在增加文本字段的值,但您最初没有设置值,因此没有什么可增加的

试着编辑你的HTML,这样你就有:

<input type="text" id="myText" value="" />

有一个小的jQuery插件可以做到这一点:https://github.com/nakupanda/number-updown

用法:

$('#textInput').updown();

查看现场演示在这里:http://jsfiddle.net/XCtaH/embedded/result/

支持键盘和鼠标滚轮事件

最新更新