[英]Image is shaking with onmouseover event
我无法通过鼠标悬停来解决图像问题。 我有以下脚本:
function displayText(id) { var el = document.getElementById(id); el.style.display = 'block'; } function hideText(id) { var el = document.getElementById(id); el.style.display = 'none'; }
.btn { margin-top: -90px; z-index: 999999999; position: absolute; text-align: center; background: #37a000; displa: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href='#' > <img class="streamer_img" alt="example" src="https://placeimg.com/640/480/nature" onmouseover="this.src='https://placeimg.com/640/480/people'; displayText('hiddentext')" onmouseout="this.src='https://placeimg.com/640/480/nature'; hideText('hiddentext')" /> <p class="btn" id="hiddentext" style="display: none;">Watch/play</p> </a>
一切都很好,但是当我将鼠标移到显示的“观看”文本上时,一切开始动摇。
我该如何解决这个问题? 谢谢
问题是因为当您将鼠标悬停在Watch
元素上时,它会触发img
上的mouseout
事件,从而更改图像。 反过来,这会隐藏文本,这会触发mouseover
以显示图像……等等。
为了解决这个问题,你可以代替附加的事件处理程序父a
元素,并找到img
内的元素来修改它,就像这样:
function displayText(id) { var el = document.getElementById(id); el.style.display = 'block'; } function hideText(id) { var el = document.getElementById(id); el.style.display = 'none'; }
.btn { margin-top: -90px; z-index: 999999999; position: absolute; text-align: center; background: #37a000; displa: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href='#' onmouseenter="this.getElementsByClassName('streamer_img')[0].src='https://placeimg.com/640/480/people'; displayText('hiddentext')" onmouseleave="this.getElementsByClassName('streamer_img')[0].src='https://placeimg.com/640/480/nature'; hideText('hiddentext')"> <img class="streamer_img" alt="example" src="https://placeimg.com/640/480/nature" /> <p class="btn" id="hiddentext" style="display: none;">Watch/play</p> </a>
请注意,我将事件处理程序更改为onmouseenter
和onmouseleave
以获得更好的性能。
但是,您应该注意,使用on*
事件属性已经过时了。 您应该改用不显眼的事件处理程序,如下所示:
window.addEventListener('load', function() { var a = document.querySelector('a'); var img = document.querySelector('img'); var p = document.querySelector('p'); a.addEventListener('mouseenter', function() { img.src = a.dataset.hoversrc; p.style.display = 'block'; }); a.addEventListener('mouseleave', function() { img.src = a.dataset.leavesrc; p.style.display = 'none'; }); });
.btn { margin-top: -90px; z-index: 999999999; position: absolute; text-align: center; background: #37a000; displa: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href='#' data-hoversrc="https://placeimg.com/640/480/people" data-leavesrc="https://placeimg.com/640/480/nature"> <img class="streamer_img" alt="example" src="https://placeimg.com/640/480/nature" /> <p class="btn" id="hiddentext" style="display: none;">Watch/play</p> </a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.