简体   繁体   English

在鼠标悬停时显示/隐藏div

[英]Show/hide div on mouse over

JavaScript: JavaScript:

$( document ).ready(function() {
    function show(id) {
        document.getElementById(id).style.visibility = "visible";
    }
    function hide(id) {
        document.getElementById(id).style.visibility = "hidden";
    }
});

And HTML: 和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 is supposed to show when the mouse hovers over the content div, but it doesn't work. Lorem ipsum应该显示在鼠标悬停在内容 div上时显示,但是它不起作用。 It is encased in a table because there are three other content divs that make a 2 by 2 grid. 它被封装在一个表中,因为还有其他三个内容div组成2 x 2网格。

show is not on the global object, it's in a closure, so when your HTML event handlers tries to call it, it doesn't exist. show不是在全局对象上,而是在闭包中,因此当您的HTML事件处理程序尝试调用它时,它不存在。

Use CSS instead 改用CSS

#text {
    visibility: hidden;
}

.content:hover #text {
    visibility: visible;
}

Your functions need to be in global scope, outside of document.ready : 您的功能需要在document.ready之外的全局范围内:

$( document ).ready(function() {
    //...
});

function show(id) {
    document.getElementById(id).style.visibility = "visible";
}
function hide(id) {
    document.getElementById(id).style.visibility = "hidden";
}

You need to define your two JavaScript functions outside of the jQuery environment/scope. 您需要在jQuery环境/范围之外定义两个JavaScript函数。

See below. 见下文。

 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> 

It's convenient to use jQuery. 使用jQuery很方便。 Also, try not to put JavaScript directly in the HTML tags. 另外,请尽量不要将JavaScript直接放在HTML标记中。 The problem here was a scope issue. 这里的问题是范围问题。

 $(".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> 

Just define the functions outside the jQuery scope. 只需在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM