我知道这不是标准的操作程序 . 但是,为了方便起见,我想了解如何使用javascripts操作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)为什么我的按钮没有大小 .
我感谢您提供的任何帮助!
1 回答
对于文本,您需要使用innerHTML或textContent:
至于大小,高度和宽度是样式属性的属性 . 您可以使用以下设置:
要么