How to hide html div

点点圈 提交于 2019-12-22 05:33:07

问题


I'm developing a small application in Ruby-On-Rails. I want to hide a div in an html.erb file until a link is clicked. What is the simplest way to do this?


回答1:


In your html file:

<a href="#" id="show_whatever">Show Whatever</a>
<div id="whatever" class="hidden">...</div>

In your CSS file:

div.hidden { display: none; }

In an included javascript file, or inside of <script> tags:

$(function() {
  $('a#show_whatever').click(function(event){
    event.preventDefault();
    $('div#whatever').toggle();
  });
});   

The hidden class is hiding the div. The jQuery function is listining for a click on the link, then preventing the link from being followed (event.preventDefault() keeps it from browsing to #)`, and lastly toggling the visibility of the div.

See the jQuery API for click() and toggle().




回答2:


This is easy with javascript. For instance, using the jQuery javascript library, you can easily toggle whether a div appears based on a link, as shown here. http://jsfiddle.net/Yvdnx/

HTML:

<a href="#">Click Me To Display Div</a>
<div>Foo</div>​

Javascript:

$(function() {
    $("div").hide();
    $("a").click(function(event) {
        event.preventDefault();
        $("div").toggle();
    });
});​

jQuery is reliable and works across many browsers, which differentiates it from using CSS3 selectors such as :target.




回答3:


You could apply the styles display:none or opacity:0. The first will make so the div doesn't take any place on your page, while the second will make it not visible, yet it will still retain his place. You could say the first hides it while the second barely masks it. There might be other solutions, but those are the two I know of.



来源:https://stackoverflow.com/questions/10340108/how-to-hide-html-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!