简体   繁体   English

如何在JavaScript中动态隐藏对象

[英]How to dynamically hide an object in javascript

I have a webpage where you can log in with your account. 我有一个网页,您可以在其中登录您的帐户。 The idea is that when you press your name a small square appears (similar to what stackoverflow does) with some of your basic information (name, email, etc.) It's a mix of php, css and javascript but the php is only to chose the name of the user. 这个想法是,当您按名称时,会出现一个小方块(类似于stackoverflow所做的事情),其中包含一些基本信息(名称,电子邮件等)。它是php,css和javascript的混合体,但是php只能选择用户名。 So, I have the following code: 因此,我有以下代码:

<style type="text/css">
table.UserInfo
{
    background-color:#000;
    width:100;
    height:100;
    position:fixed;
    top:10px;
    right:10px;
}
p.UserText
{
    color:#FFF;
}
</style>
<script type="text/javascript">
function showUser()
{
    //Unknown code here
}
</script>

In some part of the page...: Welcome visitor ! 在页面的某些部分...:欢迎访问者!

The visitor is actually set via php to a user that logged in or visitor if there is none. 访客实际上是通过php设置为登录的用户或没有访客的访客。 Here is the box: 这是盒子:

<table class='UserInfo' id='UserInfo' >
<tr>
<td><p class='UserText'>This user is a guest user. There is no information available.</p></td>
</tr>
</table>

So, I need the box to appear when I press visitor, so the code would go in showUser() and I need to know where I have to put my javascript code so the box is initially hidden. 因此,我需要在按访问者时显示该框,因此代码将进入showUser(),并且我需要知道必须将JavaScript代码放在何处,因此该框最初是隐藏的。 For the box showing when I presssed it I tried putting this code in the showUser() function: 对于按下时显示的框,我尝试将以下代码放入showUser()函数中:

document.getElementById('UserInfo')style.visibility = 'hidden';

But it didn't work. 但这没有用。 I put it hidden because it starts of as visible. 我把它隐藏了,因为它的开头是可见的。

Thank you 谢谢

您也可以这样做:

var_name = document.getElementById("idname").style.display = 'none';

That is the correct way to do it but you need to have a dot between the getElementById and the style property for the javascript code to work. 这是正确的方法,但是您需要在getElementById和style属性之间加点,以使javascript代码正常工作。 If you want to have the element start off as hidden either give it a class where 如果您希望元素以隐藏状态开始,请给它一个类,其中

visibility:hidden;

or you can put it as the inline style for the hidden element. 或者您可以将其作为隐藏元素的内联样式。 You could also do it in javascript when the load event fires but it is better to do it in the html because if the page takes a long time to render then the user will see what was supposed to be hidden until the ready event fires. 您也可以在加载事件触发时在javascript中执行此操作,但最好在html中执行此操作,因为如果页面花费很长时间呈现,那么用户将看到应该隐藏的内容,直到ready事件触发为止。 Best of luck. 祝你好运。

或jQuery:

$('.anyClass').fadeOut('fast');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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