I'm new to JQuery (and JavaScript/AJAX in general) and am encountering a problem with hiding elements.
When I use the code below the animation works and the element is hidden but as it is being hidden it is shifted onto a new line along with everything after it. This happens with horizontal hide as well but not with opacity.
Is there a way to stop this from happening or am I missing something out somewhere? The links appear on a line like this:
Related Tags: Tag1 Tag2 Tag3
Code Snippets:
HTML
<script type="text/javascript" src ="JQuery.js"></script>
<script type="text/javascript" src ="test.js"></script>
<strong>Related Tags: </strong>
<a href开发者_JS百科=#>Tag1</a>
<a href=#>Tag2</a>
<a href=#>Tag3</a>
JS
$(function() {
$("a").click(function(event){
event.preventDefault();
$(this).animate({height: 'hide' },"Fast");
});
});
Thanks in Advance,
Dave
The reason it's happening is that you're animating over the height
attribute. Manually setting height would imply block view, and that's why you're being shifted to a new line.
If you don't have a problem with it, you could switch to fadeOut
for hiding, and that probably won't cause the same error. Otherwise, the dirty workaround would have to be setting float: left
on the anchors. For this to be a neat solution, you'd have to put them in a container, and clear
them (because floating objects don't occupy any space in their parent unless they're cleared)
<p>
<a style="float: left;">...</a>
<a style="float: left;">...</a>
<a style="float: left;">...</a>
<div style="clear: both;"></div>
</p>
Shifting like that probably turns it into a block element, which will put it on a new line will visible. I would suggest:
a { float: left; }
That turns them all into blocks but keeps them side-by-side. I would also suggest using:
$(this).slideUp();
rather than animating height.
The problem is that an inline object cannot have a height specified in HTML. I'm not sure exactly what's happening here but it appears jQuery is compensating by changing the anchor to be a block-level element.
As for how to resolve it, I'm not 100% sure this will work but perhaps if you specify a style of "display: inline-block" for your anchor tags this may resolve the issue (inline-block would allow them to have a height and still behave as you'd expect). If you were to make them all "display: block; float: left;" I'm pretty sure that'd solve it too.
精彩评论