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

时间:2019-04-04 01:00:28

标签: javascript html

当您将鼠标悬停在div上时,我编写了一个Javascript函数来显示文本。我这样做是在听mouseover事件。当我的鼠标悬停在div上时,文本确实出现了,但是当鼠标悬停在该div中的新出现的文本上时,文本闪烁了。

如何阻止此文本闪烁?其他一切都正常。

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";
}

即使鼠标悬停在文本上方,我也希望文本不会闪烁。

2 个答案:

答案 0 :(得分:0)

将段落包含在HTML中,并通过在CSS中修改其display属性来简单地隐藏/显示它。

另外,正如乔希·林(Josh Lin)所说,请使用mouseentermouseleave而不是mouseovermouseout,以便在div内部过渡(从{{ 1}}至div)。

工作演示:

p
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;
}

答案 1 :(得分:0)

基于与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>