【问题标题】:Jquery hide div partiallyJquery部分隐藏div
【发布时间】:2013-04-21 20:57:10
【问题描述】:

我想在点击事件上使用 jquery 调整 div 的宽度,但我似乎无法弄清楚确切的语法是什么。

下面是我目前尝试过的一个例子。

$(function() {
    $("#square").on("click", function(){
        if($(this).css("width", "50")){
            $(this).animate({width:"500"}, 1000);
        } else {
            $(this).animate({width:"50"}, 1000);
        }
    });
});

http://jsfiddle.net/4GGP8/

提前致谢。

【问题讨论】:

标签: javascript jquery


【解决方案1】:

在你的 if 语句中尝试$(this).width() == 50,因为首先css(); 函数也会检索单位,其次你没有在 if 语句中进行这样的比较,如果有什么你应该做的@ 987654324@检索宽度并进行比较。

为了将来的参考,您可以随时使用parseInt(); 来摆脱 css 添加的单元 所以这样做也是有效的

if(parseInt($(this).css('width')) == "50")

代码:

$(function() {
    $("#square").on("click", function(){
        if($(this).width() == 50){
            $(this).animate({width:"500"}, 1000);
        } else {
            $(this).animate({width:"50"}, 1000);
        }
    });
});

这是结果 fiddle

【讨论】:

    【解决方案2】:

    试试这个 -

    jsFiddle

        $("#square").on("click", function(){
            if($(this).css('width') == '50px'){
                $(this).animate({width:"500"}, 1000);
            } else {
                $(this).animate({width:"50"}, 1000);
            }
        });
    

    【讨论】:

    • 你看过我代码中的这一行吗 - if($(this).css('width') == '50px'){
    猜你喜欢
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    • 2015-03-07
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多