【问题标题】:How to call object oriented javascript function from html如何从html调用面向对象的javascript函数
【发布时间】:2015-04-24 14:18:55
【问题描述】:

我想在事件中从 HTML 调用下面的代码(右箭头键)。

var Anim = function() {
var box = document.getElementById("square");
};
Anim.prototype.Start = function(event){
if(event.keyCode == 39){
    box.style.left = (box.offsetLeft + 100)+"px";
}
};
Anim.prototype.Stop = function(event){
if(event.keyCode == 37){
    box.style.left = (box.offsetLeft)+"px";
}
};
var Myanim = new Anim();

这是我的 HTML

<div id="square" style="position: absolute;">This is my box</div>

【问题讨论】:

  • 您的 box 变量是 Anim 构造函数的本地变量。您的 StartStop 方法将无法访问它。也许你想use a property

标签: javascript html oop


【解决方案1】:

使用 jQuery:

$(document).keypress(function(event) {
   alert('Handler for .keypress() called. - ' + event.charCode);
});

在您的项目中导入 jquery:

<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>

如果您只想使用 Javascript:

window.onkeydown = function (e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code === 37) { //left key
    alert('up');
} else if (code === 40) { //down key
    alert('down');
}};

【讨论】:

  • bt 我只想使用 javascript,没有 jquery
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-04
  • 1970-01-01
相关资源
最近更新 更多