我正在尝试创建一个文本字段和按钮,用于读取四边形的宽度和高度。输入宽度和高度,单击按钮,然后会出现带有这些规格的四边形。出于某种原因,我无法正确读取测量值,因此没有任何反应。
这就是我所拥有的:
<html>
<style>
</style>
<head>
<title>Make a Polygon!</title>
<script language="javascript">
// var element = document.createElement('div');
// element.className = "someID";
function func(form) {
var element = document.createElement('div');
element.className = "someID";
var wide = form.width.value;
document.body.appendChild(element);
// this properties work//
var a = document.getElementsByClassName('someID');
for(var i in a ){
a[i].style.zIndex='3';
a[i].style.color='rgb(255,255,0)';
a[i].style.background='rgb(0,102,153)';
//a[i].style.width=wide;
a[i].style.width='70px';
a[i].style.height='200px';
a[i].style.left='500px';
a[i].style.top='90px';
}
}
</script>
</head>
<body>
<form name="widthForm" method="get"> Width:
<input type="text" name="width" value=""> <p>
<input type="submit" name="button" value="Create" onclick="func(this.form)">
</form>
<br>
</body>
</html>
到目前为止,我只测试宽度。
部分基于此处的代码: How to Set the Left and Top CSS Positioning of a DIV Element Dynamically Using JavaScript
答案 0 :(得分:1)
您正在提交该页面,并立即刷新该页面。将提交元素更改为按钮:)
答案 1 :(得分:0)
将submit
更改为button
,并添加return false
语句以限制按钮在点击时提交表单,因为如果这样做,页面将刷新并且在javascript中添加div无法可见。试试这个:
<html>
<style>
</style>
<head>
<title>Make a Polygon!</title>
<script language="javascript">
// var element = document.createElement('div');
// element.className = "someID";
function func(form) {
var element = document.createElement('div');
element.className = "someID";
var wide = form.width.value;
var height = form.height.value;
document.body.appendChild(element);
// this properties work//
var a = document.getElementsByClassName('someID');
for(var i in a ){
a[i].style.zIndex='3';
a[i].style.color='rgb(255,255,0)';
a[i].style.background='rgb(0,102,153)';
//a[i].style.width=wide;
a[i].style.width=wide;
a[i].style.height=height;
a[i].style.left='500px';
a[i].style.top='90px';
}
}
</script>
</head>
<body>
<form name="widthForm" method="get">
Width:
<input type="text" name="width" value="">
Height:
<input type="text" name="height" value="">
<br>
<p>
<input type="button" name="button" value="Create" onclick="func(this.form);return false;">
<!-- ^^^^^^ ^^^^^^^^^^^^^-->
</form>
<br>
</body>
</html>