简体   繁体   English

当鼠标悬停在鼠标上方时如何停止mouseOver文本闪烁

[英]How to stop mouseOver text from flickering when the mouse is hovering over it

I wrote a Javascript function to display text when you hover over the div . 当您将鼠标悬停在div时,我写了一个Javascript函数来显示文本。 I did this but listening to the mouseover event. 我这样做了,但听了mouseover事件。 The text does appear when my mouse hovers over the div , but when the mouse hovers over the newly-appeared text within that div the text flickers. 当我的鼠标悬停在div ,文本会出现,但是当鼠标悬停在该div新出现的文本时,文本会闪烁。

How can I stop this text from flickering? 如何阻止此文字闪烁? Everything else is working okay. 其他一切都正常。

document.getElementById("box1").addEventListener("mouseover", mouseOver);
document.getElementById("box1").addEventListener("mouseout", mouseOut);

function mouseOver() {
    var pictureContent = document.createElement("p");
    pictureContent.innerHTML = "Officially the People's<br> Republic of China, is a <br>country in East Asia and <br>the world's most <br>populous country,";
    pictureContent.style.cssText = "position:absolute"
    document.getElementById("box1").appendChild(pictureContent);
} 

function mouseOut() {
  document.getElementById("box1").textContent = "China";
}

I would like the text not to flicker, even when the mouse is hovering over it. 我希望文本不要闪烁,即使鼠标悬停在其上也是如此。

Include the paragraph in the HTML, and simply hide/show it by modifying its display attribute in CSS. 将段落包含在HTML中,并通过在CSS中修改其display属性来简单地隐藏/显示该段落。

Also, as Josh Lin mentioned, use mouseenter & mouseleave instead of mouseover & mouseout , so that transitions inside the div (from div to p ) are not counted. 而且,如约什林所提到的,使用mouseentermouseleave代替mouseovermouseout ,从而使内部的过渡div (从divp )不计数。

Working demo: 工作演示:

 document.getElementById("box1").addEventListener("mouseenter", mouseEnter); document.getElementById("box1").addEventListener("mouseleave", mouseLeave); function mouseEnter() { document.getElementById("box_para").style.display = "block"; } function mouseLeave() { document.getElementById("box_para").style.display = "none"; } 
 #box1 { background:blue; width: 200px; height: 200px; } #box_para { display: none; } 
 <div id="box1"> China <p id="box_para">Officially the People's<br> Republic of China, is a <br>country in East Asia and <br>the world's most <br>populous country,<p> </div> 

Based on the same idea as glhr's answer, but pure css with no java script 基于与glhr答案相同的思想,但是没有Java脚本的纯CSS

 #box1 { background:red; width: 300px; height: 180px; color:yellow; padding: 6px } #box_para { color:black; display: none; } #box1:hover > #box_para { margin-left:10px; display:block !important; } 
 <div id="box1"> <h1>🇨🇳 China </h1> <p id="box_para">Officially the People's<br> Republic of China, is a <br>country in East Asia and <br>the world's most <br>populous country,<p> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM