繁体   English   中英

为什么我的动画改变宽度%高度不起作用

[英]why my animate to change width%height doesnt work

$(".btn").click(function(){
            if($($(this).parent().parent()).width() == "100%" ){
                $(this).parent().parent().stop().animate({
                    top : 0,
                    left : 0,
                    width : "500px",
                    height : "300px",
                })
            }else{
                $(this).parent().parent().stop().animate({
                    top : 0,
                    left : 0,
                    width : "100%",
                    height : "100%"
                })
            }
        })

这是我的代码。 我不知道为什么我的第一个 animation 不起作用。 将宽度设置为 100% 效果很好,但相反(到 400 像素)则不行。

.width()方法将返回以像素为单位的实际宽度。 它永远不会是"100%"

因此,您需要通过将宽度与父母的.width()进行比较来检查您的 100%

var maxwidth = $(this).parent().parent().parent().width();
if ($(this).parent().parent().width() == maxwidth) {

(我建议使用.closest("class")而不是 multiple.parent() 调用)

使用一些派生的 HTML 更新片段以演示:

 $(".btn").click(function() { console.log($("#box").width()) //if ($("#box").width() == "100%") { var maxwidth = $("#box").parent().width(); if ($("#box").width() == maxwidth) { $("#box").stop().animate({ top: 0, left: 0, width: "50px", height: "30px", }) } else { $("#box").stop().animate({ top: 0, left: 0, width: "100%", height: "100%" }) } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class='btn'> click me </button> <div id="wrapper" style='width:80px;height:50px;border:1px solid red;'> <div id="box" style='border:1px solid blue;width:50px;height:30px;'> </div> </div>

暂无
暂无

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

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