我正在页面中使用 Javascript 在 DOM 中创建元素,如下所示
var myTd_1 = document.createElement("td")
并向它们添加属性,例如
myTd_1.width='25%'
myTd_1.padding = '6'
我真的很想为 TD 添加不同的背景颜色,以防使用 onMouseOver 和 onMouseOut 事件。
我该怎么做?
我尝试在网上寻找它,但无法真正找到我需要的东西。
我用我所知道的最接近的是:
myTd_1.onMouseOver = 'this.style.backgroundColor="#042b2b"'
myTd_1.onMouseOut = 'this.style.backgroundColor="transparent"'
但它不起作用:(
最佳答案
您所要做的就是为 mouseover
和 mouseout
事件的元素添加事件监听器。您可以使用 addEventListener
来执行此操作:
var myTd_1 = document.createElement("td");
myTd_1.width='25%';
myTd_1.padding = '6';
document.getElementById('targetrow').appendChild(myTd_1);
myTd_1.addEventListener("mouseover",function(){
this.style.backgroundColor="#042b2b";
});
myTd_1.addEventListener("mouseout",function(){
this.style.backgroundColor="transparent";
});
关于javascript - 创建动态 <TD> 并添加 onMouseOver 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13562178/