我创建了Square作为对象,并给它原型大小和旋转,当我创建新的square1和square2并调用它们时,只有最后创建的div旋转,这是一个正方形,都需要旋转,&# 34;我认为它可能与className square有关,但需要帮助修复它。两个方块都需要旋转。
谢谢
// global variables //
var angle = 0; //initialize angle
// Square Object //
var Square = function() {
square = document.createElement('div');
square.className = 'square';
document.body.appendChild(square); //div created div name class square
}
// prototype size of Square
Square.prototype.size = function(width,height,margin) {
square.style.width = width + 'px';
square.style.height = height + 'px';
square.style.margin = margin + 'px';
}
//prototype rotate of Square
Square.prototype.rotate = function rotA() {
angle = (angle + 1)%360;
square.style.transform = "rotate(" + angle + "deg)"
window.requestAnimationFrame(rotA);
}
// create new square -------------
var square1 = new Square();
square1.size(250,250,250);
var square2 = new Square();
square2.size(500,500,125)
square1.rotate();
square2.rotate();
答案 0 :(得分:1)
您需要在函数中使用this
关键字。从bind
rotate
window.requestAnimationFrame
函数
// Square Object //
var Square = function() {
this.angle = 0;
this.square = document.createElement('div');
this.square.className = 'square';
document.body.appendChild(this.square); //div created div name class square
}
// prototype size of Square
Square.prototype.size = function(width,height,margin) {
this.square.style.width = width + 'px';
this.square.style.height = height + 'px';
this.square.style.margin = margin + 'px';
}
//prototype rotate of Square
Square.prototype.rotate = function() {
this.angle = (this.angle + 1)%360;
this.square.style.transform = "rotate(" + this.angle + "deg)"
window.requestAnimationFrame(this.rotate.bind(this));
}
// create new square -------------
var square1 = new Square();
square1.size(250,250,250);
var square2 = new Square();
square2.size(500,500,125);
square1.rotate();
square2.rotate();

.square {
position: absolute;
left:0;
top:0;
border: 1px solid black;
}

答案 1 :(得分:0)
检查这个fiddle,不像你希望的那样面向对象,但是如果你没有找到任何其他解决方案就可以使用它
// global variables //
var angle = 0; //initialize angle
// Square Object //
var Square = function() {
var square = document.createElement('div');
square.className = 'square';
square.style.backgroundColor = "#000";
document.body.appendChild(square); //div created div name class square
return square;
}
// prototype size of Square
Square.size = function(square, width,height,margin) {
square.style.width = width + 'px';
square.style.height = height + 'px';
square.style.margin = margin + 'px';
}
//prototype rotate of Square
Square.rotate = function rotA(square) {
angle = (angle + 1)%360;
square.style.transform = "rotate(" + angle + "deg)"
window.requestAnimationFrame(function(){ rotA(square) });
}
// create new square -------------
var square1 = new Square();
console.log(square1);
Square.size(square1,25,25,25);
var square2 = new Square();
Square.size(square2,25,25,25)
Square.rotate(square1);
Square.rotate(square2);
答案 2 :(得分:0)