When visibility: hidden
is set, no mouse events are sent to the element.
(设置“ visibility: hidden
,没有鼠标事件发送到元素。)
What you were seeing is the mouseout
event firing as the element went hidden which then caused the code to set it visible again which then triggered the mouseover
event as soon as the mouse moved - and so on.
(您所看到的是在元素隐藏时触发了mouseout
事件,然后导致代码再次将其设置为可见,然后在鼠标移动后立即触发mouseover
事件,依此类推。)
Some additional information here: Does opacity:0 have exactly the same effect as visibility:hidden
(此处提供一些其他信息: 不透明度:0与可见性具有完全相同的效果:隐藏)
Use opacity: 0
instead.
(使用opacity: 0
代替。)
Fiddle
(小提琴)
window.onload = function(){
var tag = document.getElementById('tag');
tag.style.opacity = 0;
tag.onmouseover = function () {
tag.style.opacity = 1;
}
tag.onmouseout = function () {
tag.style.opacity = 0;
}
}
If you are concerned about older browser support for opacity, you can still use visibility: hidden;
(如果您担心较旧的浏览器对不透明度的支持,则仍可以使用visibility: hidden;
不visibility: hidden;
不visibility: hidden;
)
by wrapping the tag
div in a div
with its background set to transparent
. (通过包装tag
在一个div div
与背景设定为transparent
。)
Attach the mouseover/mouseout handlers to the wrapping div and change the visibility of the child.
(将mouseover / mouseout处理程序附加到包装div并更改子级的可见性。)
This avoids the repeated mouseover/mouseout events as the wrapper will always receive mouse events. (这样可以避免重复的mouseover / mouseout事件,因为包装程序将始终接收鼠标事件。)
Demo 2:
(演示2:)
HTML:
(HTML:)
<div style='position:relative'>
<div id='tag' style='position : absolute; top: 20px; left: 20px; width: 50px; height: 50px; z-index: 10; background: transparent;'>
<div id='tagInner' style=' border: 1px solid red; position : absolute; top: 0; left: 0; right: 0; bottom: 0;'>
</div>
</div>
<img src='http://www.hihowareyou.com/store/images/products/tn_HiVinylFrontmed.jpg' id='wow'>
</div>
Code:
(码:)
var tag = document.getElementById('tag');
var tagInner = document.getElementById('tagInner');
tagInner.style.visibility = 'hidden';
tag.onmouseover = function () {
tagInner.style.visibility = 'visible';
}
tag.onmouseout = function () {
tagInner.style.visibility = 'hidden';
}
There is also an interesting writeup on CSSTricks about CSS Transparency Settings for All Browsers .
(关于所有浏览器的CSS透明度设置,关于CSSTricks的文章也很有趣。)
I haven't tried that approach myself with older browsers, but it may work for you. (我没有在较旧的浏览器中尝试过这种方法,但是它可能对您有用。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…