プロトタイプと jQuery ライブラリを使用しました。しかし、私は OOP JS をもっと幅広く学びたいと思っています。私がやりたいことは、JS オブジェクトの複数のインスタンスを作成して同時に実行することです。ここで作業している例では、跳ね回る 7 つの異なるボックスを作成したいと考えています。プロトタイプを使用してオブジェクトを複数回作成する最良の方法を読みました。これは、私が作成した実用的なスクリプトの例です。
私が遭遇する問題は、「this.int = setInterval(this.move,20);」のコメントを外すと、move 関数で「this.box.style.left」が見つからないというエラーが表示されることです。 . バウンスオブジェクトから移動機能が壊れているようです。私はこれを機能させるために考えられるすべてを試しました。オブジェクトの変数としてintを使用する必要があるため、停止関数を作成してそれを強制終了できます。
「bounce.prototype.stop = function() { clearInterval(this.int); });」のように
HTML
<body onload="dothis()">
<div id="case">
<div class="boxclass" id="box1">BOX</div>
</div>
</body>
CSS
<style type="text/css">
body {
background-color: #3F9;
text-align: center;
margin: 0px;
padding: 0px;
}
#case {
background-color: #FFF;
height: 240px;
width: 480px;
margin-right: auto;
margin-bottom: 72px;
position: relative;
margin-top: 72px;
margin-left: auto;
}
.boxclass {
background-color: #F96;
height: 36px;
width: 36px;
position: absolute;
}
</style>
ジャバスクリプト
<script type="text/javascript">
function bounce(frame,box,speed,x,y) {
this.speed = speed;
this.frame = frame;
this.box = box;
this.fw = frame.offsetWidth;
this.fh = frame.offsetHeight;
this.bx = x;
this.by = y
this.int = '';
return this;
}
bounce.prototype.position = function () {
if (this.box.offsetLeft <= 0 && this.bx < 0) {
console.log('LEFT');
this.bx = -1 * this.bx;
}
if ((this.box.offsetLeft + this.box.offsetWidth) >= this.frame.offsetWidth) {
console.log('RIGHT');
this.bx = -1 * this.bx;
}
if (this.box.offsetTop <= 0 && this.by < 0) {
console.log('TOP');
this.y = -1 * this.y;
}
if ((this.box.offsetTop + this.box.offsetHeight) >= this.frame.offsetHeight) {
console.log('BOTTOM');
this.y = -1 * this.y;
}
return this;
}
bounce.prototype.move = function() {
this.box.style.left = this.box.offsetLeft + this.bx+"px";
this.box.style.top = this.box.offsetTop + this.by+"px";
//this.int = setInterval(this.move,20);
}
function dothis() {
bn1 = new bounce( document.getElementById('case'), document.getElementById('box1'), 10,20,30).position();
bn1.move();
}
</script>