JavaScript图像在onmouseover和onmouseout上闪烁

时间:2017-11-03 02:41:39

标签: javascript html

我正在尝试鼠标悬停以弹出较大的默认图像。但是,每当我将鼠标悬停在较小的图像上时,它都会弹出,但是当我将鼠标悬停在弹出图像上时,它会一直闪烁。

以下是我的代码:

HTML:

<div class="thumbnail" id="thumbnail1">
    <img src="image1.jpg" onmouseover="enlarge1()" onmouseout="minimize1()"/>            
</div>

JS:

function enlarge1() {
    var parent = document.getElementById("thumbnail1");
    var child = document.createElement("IMG");
    child.setAttribute("src", "image-large1.jpg");
    child.setAttribute("width", "350%");
    child.setAttribute("alt", "Related Large 1");
    child.style.position="absolute";
    child.style.zIndex="1";
    child.style.bottom="15%";
    child.style.left="30%";

    parent.appendChild(child);

}

function minimize1() {
    var parent = document.getElementById("thumbnail1");
    var child = parent.lastElementChild;
    parent.removeChild(child);
}

3 个答案:

答案 0 :(得分:3)

你需要......

  1. 将鼠标事件移动到包装div

  2. 将其更改为onmouseenteronmouseleave

  3. <div class="thumbnail" id="thumbnail1" onmouseenter="enlarge1()" onmouseleave="minimize1()">
        <img src="image1.jpg" alt=''>
    </div>
    

    这样,当你将鼠标悬停在 图像上时,它仍然在&#34;悬停&#34;模式 - 而且,与onmouseover不同,onmousenter仅触发一次(当您输入div时),因此当您从悬停在小图像上切换到大图像时,它不会重新触发。

答案 1 :(得分:0)

您可以使用mouseenter和mouseleave,而不是鼠标悬停和鼠标移除。

因为只要将鼠标移到DOM或它的子DOM上,就会调用mouseover事件。因此,当您将鼠标移动到较大的图像上时,可能会多次调用它。

但是,对于mouseenter,只有当你输入DOM时,它才会被调用,而不是它的孩子。将鼠标移动到较大的图像上时不会调用它。

&#13;
&#13;
var x = 0;
var z = 0;
function myEnterFunction() {
    document.getElementById("demo2").innerHTML = x+=1;
}
function myMoveFunction() {
    document.getElementById("demo").innerHTML = z+=1;
}
&#13;
div {
    width: 100px;
    height: 100px;
    border: 1px solid black;
    margin: 10px;
    float: left;
    padding: 30px;
    text-align: center;
    background-color: lightgray;
}

p {
    background-color: white;
}
&#13;
<div onmouseenter="myEnterFunction()">
<img style="width: 100px;height: 100px;background-color:red;" src="" title="move mouse enter here"  />
<p>onmouseenter: <br> <span id="demo2">Mouse over me!</span></p>
</div>
<div onmousemove="myMoveFunction()">
  <p>onmousemove: <br> <span id="demo">Mouse over me!</span></p>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

自编写此书以来,我发现它只是部分成功。

按照建议,我使用mouseenter并在图上而不是图像上退出。 在mouseenter上,我增加了图的尺寸以进行强调。 将鼠标指针恰好放在数字之间会不断闪烁,所以我尝试了 增加数字上的边距并停止闪烁。 反复试验为我提供了有效的解决方案,但数字之间没有太大的差距。 看起来直到您到达图中的元素之一,mouseenter才可能触发 也许使用焦点的东西会提供更优雅的解决方案。 希望这对某人有帮助