使用纯JS创建具有id和样式的元素
Create Element with id and styles using pure JS
我构建了一个小函数,该函数附加了一个带有id和样式的元素。知道我的问题为什么这个代码不起作用吗?
window.addEventListener("load",function(e){
var inButton = document.createElement("DIV"),
body = document.body;
inButton.id = "button";
inButton.style = function (){
height = "200px";
width = "400px";
position = "fixed";
top = "50%";
left = "50%";
marginLeft = -1*(this.width / 2);
marginTop = -1*(this.height / 2);
};
body.appendChild(inButton);
}, false);
我使用以下html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="description"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<script type="text/javascript" src="js/vendor/modernizr-.8.3.min.js"></script>
</head>
<body>
<script type="text/javascript" src="js/plugins.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
Js代码在main.Js.中
我一遍又一遍地检查路径,但路径完全正确。
您没有正确设置style
属性。其余代码正确。
这里有一个例子
window.addEventListener("load", function(e) {
var inButton = document.createElement("DIV"),
body = document.body;
inButton.id = "button";
inButton.innerHTML = "Yahooooooooooooooo"; //For example
inButton.style.height = "200px";
inButton.style.width = "400px";
inButton.style.position = "fixed";
inButton.style.top = "50%";
inButton.style.left = "50%";
inButton.style.marginLeft = -1 * (this.width / 2);
inButton.style.marginTop = -1 * (this.height / 2);
body.appendChild(inButton);
}, false);
相关文章:
- 一个正则表达式,用于从JS中的HTML标记中删除id、样式和类属性
- ID为的HTML样式类
- 使用getElementById设置动态ID的输入字段的样式
- 如何使用随机css id为元素设置样式
- css样式加载+id.例如加载1、加载300
- 将样式表链接到 ID
- 按 ID 包含子字符串的类查找元素并更改样式
- 使用Jquery更改css样式适用于id's、 不在课堂上
- 使用纯JS创建具有id和样式的元素
- 将 ID 选择器注入样式
- 获取 document.activeElement.id 的样式属性
- Stylus:为在 JavaScript 中生成的 ID 添加样式
- 当样式使用相同的 id 时,如何在 KML 文件中重新着色多边形
- 使用 JavaScript 在 iframe 中通过 ID 更改元素的 CSS 样式
- 如何找出 id 部分匹配的元素,并更改其 css 样式
- 如何使用相同 id 的 javascript 检查输入中的值,并仅更改小于 1.5 的输入的边框样式
- 如何在具有相同样式但不同 ID 的输入元素上使用按钮作为微调器
- 样式表是否可以获得一个类或id来动态更改它
- 具有唯一id的CKEDITOR样式
- 根据ID加载css样式表