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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15742027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:56:16  来源:igfitidea点击:

How to get an H1 text inside a div through an omouseover event and innerHTML property

javascriptdominnerhtmlonmouseover

提问by Naima

I'm trying to write the content of my H1 inside a div when I put the mouse over the H1, but only get [Object HTMLHeadingElement], not the text itself. I'm a total beginner and I'm trying it with the innerHTML property. Thank you all!

当我将鼠标放在 H1 上时,我试图将 H1 的内容写入 div 中,但只得到 [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;
    }
}

回答by David says reinstate Monica

You have three options to get the text-content:

您有三个选项来获取文本内容:

// 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;

For efficiency, with the following HTML:

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

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

I'd suggest:

我建议:

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.

JS小提琴演示

回答by miorel

Try div2.innerHTML = text.innerHTML;

尝试 div2.innerHTML = text.innerHTML;