为动态创建的元素设置属性

Set attribute for dynamicaly created element

本文关键字:设置 属性 元素 动态 创建      更新时间:2023-09-26

我们使用以下代码片段在插件中创建JavaScript div元素。

代码片段:

var temp = document.createElement('div');     

但我无法将样式应用于此div。您能否对此进行任何调查,并为以下事项提供建议。这对我们非常有帮助。

  • 如何为创建的div 添加类?
  • 如何将样式应用于该特定div?
  • 如何为该div 调用 onscroll 事件?

试试这个:

var temp = document.createElement('div');
temp.className = "yourclass";
temp.style.cssText = 'width:100px; height:100px'; //example
temp.onscroll = function() 
{ 
 alert('on scroll');
}; 

演示

试试这个

var ele = document.createElement('div')
var id = 'temp'
ele.setAttribute('id', id)

导致

<div id="temp"></div>

我建议你看看JavaScript的基础知识,以便理解它的功能。

如果你看一下 JavaScript 的小型初学者教程,你会学到你问的大部分东西。它们非常非常基本,应该搜索,而不是在stackoverflow上询问。只需像这样使用谷歌。没那么难,是吗?

但是,这里仍然是您问题的答案。我知道有几种方法可以做某些事情。以下代码片段应该适用于所有常见浏览器。

添加类

若要设置元素的类,可以使用 setAttribute 方法。

temp.setAttribute("class", "myclass");

应用样式

每个元素都有一个 style 属性,您可以使用该属性来更改可以使用 CSS 更改的任何内容。

temp.style.backgroundColor = "#000000";
temp.style.color = "#FFFFFF";
temp.style.fontSize = "24pt";

侦听事件

可以使用onsomething属性或attachEvent(Internet Explorer)和addEventListener(其他浏览器)向元素添加事件侦听器。

方法 1 - 某些属性:

使用元素的 onscroll 属性,可以一次应用一个事件侦听器。这是最简单的方法,所有浏览器都支持。

temp.onscroll = function(e) {
    // Do something
};

方法 2 - 附加事件和添加事件侦听器:

使用 addEventListener ,如果需要,可以应用多个事件侦听器。大多数时候,这是首选方式。旧版本的IE浏览器不支持addEventlistener,因此在这种情况下您必须使用attachEvent

// Check if the browser supports addEventListener
if (temp.addEventListener) {
    // If it does support addEventListener, use it
    temp.addEventListener("scroll", onScroll);
} else if (temp.attachEvent) {
    // If it does not support addEventListener, use attachEvent instead
    temp.attachEvent("onScroll", onScroll);
}
function onScroll(event) {
    // Do something
}

试试这个

var temp = document.createElement('div');   
temp.setAttribute('class', 'someClassName');
temp.setAttribute('Id', 'MyDiv');

您可以设置任何 css 属性来分配类,在本例中为"someClassName",同样,您可以调用任何针对分配的 ID 的函数,即"myDiv"

希望这有帮助

[编辑]这是一个工作小提琴: http://jsfiddle.net/NHBr2/

您现在已经在 temp 变量中创建了"div"。为了设置样式,请使用此代码。

内联样式:

temp.setAttributes('style','width:100px;');

添加类:

temp.setAttributes('class','myClass');

添加 ID:

temp.setAttributes('id','MyID');

添加偶数:

temp.setAttributes('OnMouseWheel','myFunction(e);');