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

Nai*_*ima 0 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*mas 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;
Run Code Online (Sandbox Code Playgroud)

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

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

我建议:

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));
}
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.