0

私はこのように私のページでJavascriptを使用してDOMで要素を作成しています

var myTd_1 = document.createElement("td")

それらにプロパティを追加すると、

myTd_1.width='25%'
myTd_1.padding = '6'

onMouseOverイベントとonMouseOutイベントを使用する場合に備えて、TDに異なる背景色を追加したいと思います。

どうすればいいですか?

ネットで探してみましたが、本当に必要なものが見つかりませんでした。

私が知っているものを使用して私が思いついた最も近いものは:

myTd_1.onMouseOver = 'this.style.backgroundColor="#042b2b"'
myTd_1.onMouseOut = 'this.style.backgroundColor="transparent"'

しかし、それは機能していません:(

4

4 に答える 4

2

あなたがしなければならないのは、mouseoverandmouseoutイベントの要素にイベントリスナーを追加することです。あなたはこれを使用して行うことができます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";
});
于 2012-11-26T09:51:02.777 に答える
1

これを試して:

   myTd_1.onmouseover = function() {
      myTd1.style.backgroundColor = "#042b2b";
   }

   myTd_1.onmouseout = function() {
      myTd1.style.backgroundColor = "transparent";
   }
于 2012-11-26T09:53:01.057 に答える
1

これを試して ....

myTd_1.onmouseover = 'this.style.backgroundColor="#042b2b"';
myTd_1.onmouseout = 'this.style.backgroundColor="transparent"';
于 2012-11-26T09:53:12.087 に答える
1

より動的な方法でIDを使用せずにこれを行うことができます。

これが実際の例です

これが私が使用したコードです:

/* get the table td elements */
var tdCollection = document.getElementById('main').getElementsByTagName('td'),
    i = 0,
    bgClassName = 'mouseover';

function removeClass(element, className) {
    element.className = element.className.replace(new RegExp('(\\s|^)' +  className + '(\\s|$)', 'g'), '');
}

while (tdCollection[i]) {
    tdCollection[i].addEventListener('mouseover', function () {
        /* adding the class to change bgcolor */
        this.className += ' mouseover'; 
    });
    tdCollection[i++].addEventListener('mouseout', function () {
        /* removing the bgcolor changing class */
        removeClass(this, bgClassName);  
    });
};
​
于 2012-11-26T13:39:21.467 に答える