问题
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