gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 12:01:30 25 4
gpt4 key购买 nike

当我将鼠标放在 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;
}
}

最佳答案

您可以通过三个选项来获取文本内容:

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

关于javascript - 如何通过 omouseover 事件和 innerHTML 属性获取 div 内的 H1 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15742027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com