当鼠标越过按钮时,我希望它隐藏起来,当鼠标离开按钮时,我希望按钮重新出现。但我需要使用onmouseover和onmouseout。
null
<script>
function money ()
{
document.getElementById("1").style.display = "none";
}
function cash ()
{
document.getElementById("1").style.display = "block";
}
</script>
<input type="button" value="Hi" id="1" onmouseover="money('')" onmouseout="cash('')" >
null
问题是,当光标进入按钮时,mouseover事件被激发,元素消失,mouseout事件被激发,因为元素消失了,因此鼠标不再在其中。您需要将按钮放入一个div中,并在该div上执行鼠标操作。
您已经知道,这可以使用CSS的:hover
...
但这里有一个JS方法:
null
function money (el){
el.style.opacity = 0;
}
function cash (el){
el.style.opacity = 1;
}
<input type="button" value="Hi" onmouseenter="money(this)" onmouseleave="cash(this)">
这里是纯JS方式:注意,与其他答案类似的按钮会抖动:https://jsfidle.net/omarjmh/6o2nc754/1/
var x = document.getElementById("myBtn");
x.addEventListener("mouseenter", myFunction);
x.addEventListener("mouseout", mySecondFunction);
function myFunction() {
document.getElementById("myBtn").style.display = "none";
}
function mySecondFunction() {
document.getElementById("myBtn").style.display = "block";
}