初始化DIV中的按钮元素

Initializing a Button Element in a DIV

本文关键字:按钮 元素 DIV 初始化      更新时间:2023-09-26

我知道这不是标准操作程序。但是,为了方便起见,我想了解如何使用javascript操作HTML按钮元素。特别是,我很难复制以下陈述中的省略号部分:

<button type="button">...</button>

我的意思是:我已经使用脚本向div添加了一个按钮,但我无法在按钮本身上获得标签。这是我迄今为止使用的代码:

var	body,
	adc = adc || {}; 
adc.containers = {
	bdrStyleOps: ['hidden', 'dotted', 'dashed', 'solid', 'double', 'groove', 'ridge', 'inset', 'outset'],
	bdrWidthOps: ['thin', 'medium', 'thick', '10px', '15px', '25px'],
	addHead: function() {
		var mainHead = this.addDiv('Main Header', 40, 0, -1, 45, 600, this.bdrStyleOps[3], this.bdrWidthOps[1], 'green', 10);
		var btn = document.createElement('button');
		btn.setAttribute('name', 'head button 1');
		btn.setAttribute('height', '30px');
		btn.setAttribute('width', '30px');
		btn.setAttribute('type', 'button');
		btn.setAttribute('value', 'HELLO BUTTON');
		mainHead.appendChild(btn);
		body.appendChild(mainHead);
	},
      
	addDiv: function(ID, x, y, z, h, w, bStyle, bWidth, bColor, bRadius) {
		var obj = document.createElement('div');
		obj.id = ID;
		obj.style.position = 'absolute';
		obj.style.top = y + 'px';
		obj.style.left = x + 'px';
		obj.style.height = h + 'px';
		obj.style.width = w + 'px';
		obj.style.zIndex = z;
		obj.style.borderStyle = bStyle;
		obj.style.borderWidth = bWidth;
		obj.style.borderColor = bColor;
		obj.style.borderRadius = bRadius + 'px';
		obj.style.textAlign = 'left';
		obj.style.verticalAlign = 'middle';
		obj.style.padding = '0px 0px 0px 0px';
		obj.style.whiteSpace = 'pre-wrap';
		
		return obj;
	},
	
 	init: function() {
		body = document.getElementById('body');
		this.addHead();
	}
}
<!DOCTYPE html>
<html>
	<head>
	</head>
	<body id="body">
		<script src="globals.js">
		</script>
		<script src="content.js">
		</script>
		<script src="CSS.js">
		</script>
		<script>
			document.addEventListener('DOMContentLoaded', function () {
				adc.containers.init();
			});
		</script>
	</body>
</html>

这段代码生成一个div,它有一个绿色边框和左上角的一个按钮。问题是,按钮没有尺寸。在Chrome开发人员视图中,检查该按钮显示高度和宽度设置为30px,但该按钮仍然很小。

其次,我还没有找到设置按钮文本值的方法。"value"属性无法实现这一点,我只找到了对html初始化的引用,该初始化将文本放在标记之间:

<button type="button">LABEL TEXT</button>

我想知道如何:1)使用java设置LABEL TEXT;2)为什么我的按钮没有大小。

我感谢你能提供的任何帮助!

对于需要使用innerHTML或textContent:的文本

btn.textContent = 'LABEL TEXT';

至于大小,高度和宽度是样式属性的属性。您可以设置它们:

btn.setAttribute('style','height:30px; width:30px');

btn.style.height = '30px';
btn.style.width = '30px';