简体   繁体   English

单击按钮时动画div的高度

[英]Animate height of div when button is clicked

I'm trying to animate a drop down menu div's height from 0 to 250px, when the menu button is clicked. 单击菜单按钮时,我试图设置下拉菜单div的高度从0到250px的动画。 I tried using jQuery. 我尝试使用jQuery。

This is included in my HTML: 这包含在我的HTML中:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script src="scripts.js"></script>

The menu button is a span: 菜单按钮是一个跨度:

<span id="menu_btn" name="menu_button">MENU</span>

And this is the drop down menu: 这是下拉菜单:

<div id="menu_dropdown">
    <ul>
        <li><a id="on" href="#">HOME</a></li>
        <!-- more buttons -->
</div>

And this is the jQuery: 这就是jQuery:

$("#menu_btn").toggle(function(){
    $("#menu_dropdown").animate({'height': '250px'}, 100);
}, function(){
    $("#menu_dropdown").animate({'height': '0px'}, 100);
});

However it doesn't work. 但是,它不起作用。 Why is this? 为什么是这样?

I think this is what you want: 我认为这是您想要的:

$("#menu_btn").on('click', function() {
    $("#menu_dropdown").slideToggle(100);
});

Changing the height will probably not work because the it will not prevent the content for being shown. 更改高度可能不会起作用,因为它不会阻止内容显示。 slideToggle() changes the display property, which will work. slideToggle()更改display属性,该属性将起作用。

See also http://api.jquery.com/slideToggle/ 另请参阅http://api.jquery.com/slideToggle/

Span is not a button or anchor tag. 跨度不是按钮或锚标记。 Also you need to catch a click event first in order to use toggling. 另外,您需要先捕获一个点击事件才能使用切换。

http://jsfiddle.net/3w2tt1wm/ http://jsfiddle.net/3w2tt1wm/

Take alook

Try using anonymous functions in your animate calls instead like below. 尝试在动画调用中使用匿名函数,如下所示。 Then you can explicitly get the element you want to change the height for and do it using jquery's .height(HEIGHT) or .css("height", HEIGHT); 然后,您可以显式获取要更改其高度的元素,并使用jquery的.height(HEIGHT)或.css(“ height”,HEIGHT);进行更改。

$("#menu_btn").toggle(function(){
    $("#menu_dropdown").animate(function(){$("#menu_dropdown").css("height", "250px");}, 100);
}, function(){
    $("#menu_dropdown").animate(function(){$("#menu_dropdown").css("height", "0px");}, 100);
});

Also, you didn't show it so just make sure the toggle is in a click or mouseover handler function. 另外,您没有显示它,因此只需确保切换位于单击或鼠标悬停处理函数中即可。 It won't do you any good otherwise. 否则,它对您没有任何好处。

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

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