[英]Show/hide div on mouse over
JavaScript:
$( document ).ready(function() {
function show(id) {
document.getElementById(id).style.visibility = "visible";
}
function hide(id) {
document.getElementById(id).style.visibility = "hidden";
}
});
和HTML:
<table>
<tr>
<td id="one">
<div class="content" onMouseOver="show('text')" onMouseOut="hide('text')">
<h1>Heading</h1>
<p id="text">Lorem ipsum</p>
</div>
</div>
</td>
</table>
Lorem ipsum应该显示在鼠标悬停在内容 div上时显示,但是它不起作用。 它被封装在一个表中,因为还有其他三个内容div组成2 x 2网格。
show
不是在全局对象上,而是在闭包中,因此当您的HTML事件处理程序尝试调用它时,它不存在。
改用CSS
#text {
visibility: hidden;
}
.content:hover #text {
visibility: visible;
}
您的功能需要在document.ready
之外的全局范围内:
$( document ).ready(function() {
//...
});
function show(id) {
document.getElementById(id).style.visibility = "visible";
}
function hide(id) {
document.getElementById(id).style.visibility = "hidden";
}
您需要在jQuery环境/范围之外定义两个JavaScript函数。
见下文。
function show(id) { document.getElementById(id).style.visibility = "visible"; } function hide(id) { document.getElementById(id).style.visibility = "hidden"; }
.content { border: 1px dotted blue; } #text { visibility: hidden; }
<table> <tr> <td id="one"> <div class="content" onMouseOver="show('text');" onMouseOut="hide('text')"> <h1>Heading</h1> <p id="text">Lorem ipsum</p> </div> </div> </td> </table>
使用jQuery很方便。 另外,请尽量不要将JavaScript直接放在HTML标记中。 这里的问题是范围问题。
$(".content").hover(function() { $("#text").show(); }, function() { $("#text").hide(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table> <tr> <td id="one"> <div class="content"> <h1>Heading</h1> <p id="text">Lorem ipsum</p> </div> </div> </td> </table>
只需在jQuery范围之外定义函数即可。
<script>
function show(id) {
document.getElementById(id).style.visibility = "visible";
}
function hide(id) {
document.getElementById(id).style.visibility = "hidden";
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.