Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Всем доброго вечера, пожалуйста помогите (https://javascript.ru/forum/misc/18899-vsem-dobrogo-vechera-pozhalujjsta-pomogite.html)

kazimira6 19.07.2011 21:31

Всем доброго вечера, пожалуйста помогите
 
Я не могу понять, как мне обратиться к объекту createOne, как к элементу DOM, для того чтобы присвоить ему стиль через джаваскрипт. Пожауйста, помогите, я только учусь...)
<script type="text/javascript">
function createObj(element) {
this.create = function(){
cube = document.createElement("div");
cube.className = "cube";
document.body.appendChild(cube);
}
this.positionLeft ="positionLeft";
this.positionTop ="positionTop"
}
var createOne = new createObj();
for(var i=0; i<30; i++){
createOne.create()
}
</script>


Заранее благодарна...

trikadin 19.07.2011 21:45

К объекту createOne, как к элементу DOM'а, обратиться нельзя. Потому что это не элемент DOM. Элементами DOM являются объекты, которые создаются ф-цией create. К ним можно обратиться, использую класс "cube", например. А можно - используя св-во style. Пример:

<body>
<style>
.cube {
 background: red;
 width: 20px;
 height: 10px;
 margin-bottom: 2px;
};
</style>
<script type="text/javascript">
function createObj(element) {
 this.create = function(bckg){ // принимает аргументом цвет фона
 var cube = document.createElement("div"); // обратите внимание на var - без этого ключевого слова переменная будет глобальной.
 cube.className = "cube";
 if (bckg) // если параметр существует
  cube.style.backgroundColor=bckg; // то ставим цвет фона
 document.body.appendChild(cube);
}
 this.positionLeft ="positionLeft"; // зачем эти строки?
 this.positionTop ="positionTop"
}
var createOne = new createObj();

for(var i=0; i<5; i++){
 createOne.create() // создаём элементы с фоном по умолчанию
}

for(var i=0; i<5; ++i){
 createOne.create("blue"); // создаём эл-ты с синим фоном
};
</script>
</body>


Лучше стили ставить через классы/идентификаторы.

kazimira6 19.07.2011 21:48

Спасибо Вам огромное, trikadin! Теперь я поняла, в чем моя ошибка)

kazimira6 19.07.2011 22:21

Благодаря trikadin, получилось то, что хотела реализовать. Не судите строго, я пока мало знаю.) И код, который получился - очень не красивый!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
	"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<head>
<title>Animation Javascrip</title>
<style type="text/css">
#wrapper{width:600px; margin:0 auto; background:#dedede; position:relative;}
.cube{width:1px; height:1px; background:#000000; position:absolute; left:0;}
</style>

</head>
<body>
<div id="wrapper">
<form id="num" action="" method="">
<input type="text" name="field" />
<input type="button" value="вперед" id="but" />
</form>
<script type="text/javascript">
function createObj(element) {
	this.create = function(bgColor, posL, posT){
	cube = document.createElement("div");
	cube.className = "cube";
	if(bgColor){cube.style.backgroundColor=bgColor;}
	if(posL){cube.style.left=posL;}
	if(posT){cube.style.top=posT;}
	document.body.appendChild(cube);
	}
}
but = document.getElementById("but");
	but.onclick = function(){
	numV = Math.round(document.getElementById("num").field.value);
	var createOne = new createObj();
	for(var i=0; i<numV; i++){
	createOne.create("blue", (i/2+"px"), i+"px")
	}
}
</script>
</div>
</body>


На форуме очень много умных разработчиков, может кто-нибудь подскажет, как его улучшить. Заранее спасибо...)

trikadin 20.07.2011 01:56

Стилевые свойства не пишите в строчку. Код можно укоротить примерно так:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<head>
<title>Animation Javascrip</title>
<style type="text/css">
#wrapper {
 width:600px;
 margin:0 auto;
 background:#dedede;
 position:relative;
}

.cube {
 width:1px;
 height:1px;
 background:#000000;
 position:absolute;
 background: blue;
}
</style>
 
</head>
<body>
<div id="wrapper">
<form id="num" action="" method="">
<input type="text" name="field" />
<input type="button" value="вперед" id="but" />
</form>
<script type="text/javascript">
create = function(posL, posT) {
 var cube = document.createElement("div");// ну я же говорил - обратите внимание на "var"!
 cube.className = "cube";
 cube.style.left=posL; // здесь проверка if не обязательна - предполагается, что этот параметр будет передан обязательно.
 cube.style.top=posT; // и тут тоже. В той ф-ции я использовал if, чтобы в случае, если передан цвет, то ставить его, а если нет - оставлять цвет по умолчанию. Здесь же "умолчания" нет, так что смело убираем if...
 document.body.appendChild(cube);
};

document.getElementById("but").onclick = function(){
 var numV = Math.round(document.getElementById("num").field.value);
 for(var i=0; i<numV; i++) {
  create(i/2+"px", i+"px");
 }
}
</script>
</div>
</body>

kazimira6 20.07.2011 10:38

Да, действительно, я многое упустила. Спасибо, trikadin, что подкорректировали мой код. Вы настоящий профессор!)


Часовой пояс GMT +3, время: 09:24.