如何通过omouseover事件和innerHTML属性在div中获取H1文本

时间:2013-04-01 10:49:32

标签: javascript dom innerhtml onmouseover

当我将鼠标放在H1上时,我试图在div中写入H1的内容,但只获取[Object HTMLHeadingElement],而不是文本本身。我是一个初学者,我正在尝试使用innerHTML属性。谢谢大家!

HTML code:

<h1 id="phrase" onmouseover="writeInDiv2()">Hi all</h1>

JavaScript code:

var text = document.getElementById("phrase");

function writeInDiv2(){
    if(div2.style.display != "none"){
        div2.innerHTML = text;
    }
}

2 个答案:

答案 0 :(得分:6)

您可以通过三种方式获取文字内容:

// Webkit, Mozilla, Opera (and other standards-compliant) browsers
var text = document.getElementById("phrase").textContent;

// Microsoft Internet Explorer (though this might have changed in IE 10)
var text = document.getElementById("phrase").innerText;

// Possibly works, though assumes the h1 contains only a text-node
var text = document.getElementById("phrase").firstChild.nodeValue;

为提高效率,请使用以下HTML:

<h1 onmouseover="writeInDiv2(this, 'div2')">Hi all</h1>
<h1 onmouseover="writeInDiv2(this, 'div2')">Another message</h1>
<div id="div2"></div>

我建议:

function writeInDiv2(el, textInto){
    var div2 = textInto.nodeType === 1 ? textInto : document.getElementById(textInto),
        text = el.textContent ? el.textContent : el.innerText;
    while (div2.firstChild){
        div2.removeChild(div2.firstChild);
    }
    div2.appendChild(document.createTextNode(text));
}

JS Fiddle demo

答案 1 :(得分:1)

尝试div2.innerHTML = text.innerHTML;