jQuery addClass 函数似乎在运行,但实际上并未填充类名

标签 jquery html css

我在这里遇到了一个奇怪的问题。

我开发了一个包含多个操作的搜索框。重要的是,当用户单击按钮时,它将(或者应该...)打开。

HTML:

<form method="get" id="searchform" action="">
    <input type="search" placeholder="Search" size="18" value="" name="s" id="s" />
    <input type="submit" value=""></input>
</form>

CSS:

#searchform {
    position: relative;
    min-width: 40px;
    height: 80px;
    float: right;
}
#searchform input[type="search"] {
    margin-right: 40px;
    height:80px;
    width:2px;
    background:rgba(245, 245, 240, 1);
    padding: 0;

    -webkit-transition:all .2s ease-in-out;
    -moz-transition:all .2s ease-in-out;
    -o-transition:all .2s ease-in-out;
    transition:all .2s ease-in-out;
}
#searchform input[type="submit"] {
    background: rgba(255, 255, 255, 1);
    position: absolute;
    right: 0;
    top: 0;
    width: 40px;
    height: 80px;
}
#searchform.open input[type="search"] {
    width: 180px;
    padding: 0 0 0 20px;
}
#searchform.open input[type="submit"] {
    background:rgba(200, 160, 0, 1);
}

JS:

$('#searchform input[type="submit"]').click(function () {
    $("#searchform").toggleClass('open');
});

$('#searchform input[type="submit"]').click(function () {
    if ($('#searchform').hasClass('open') && $.trim($('#searchform input[type="search"]').val()).length === 0) {
        event.preventDefault();
        $('#searchform').removeClass('open');
    }
});

$(document).bind('click', function () {
    $('#searchform').removeClass('open');
});

$('#searchform').bind('click', function (event) {
    event.stopPropagation();
});

这是一个 fiddle :http://jsfiddle.net/5zB8f/1/

<小时/>

打开操作非常简单。 jQuery 脚本将 class="open" 添加到 #searchform,但它只是添加类......代码似乎有效,所以我不知道为什么它会表现得像这样。

如果您手动将该类添加到 html 并运行它,您将看到它应该转换到的内容。

感谢任何帮助。如果有人能告诉我如何优化该 jQuery 脚本,我会加分...我确信我已经编写了超出其工作所需的内容...

<小时/>

编辑:我现在已经有了 toggleClass,但它的行为与 addClass 相同...

最佳答案

这是您需要的吗?

http://jsfiddle.net/5zB8f/3/

$('#searchform input[type="submit"]').click(function () {
    $("#searchform").toggleClass('open');
    if ($('#searchform').hasClass('open') && $.trim($('#searchform input[type="search"]').val()).length === 0) {
        event.preventDefault();
    }
    if ($("#searchform").hasClass("open")) return false;
});


$(document).bind('click', function () {
    $('#searchform').removeClass('open');
});

$('#searchform').bind('click', function (event) {
    event.stopPropagation();
});

关于jQuery addClass 函数似乎在运行,但实际上并未填充类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19577162/

相关文章:

jquery - 按类名递归查找下一部分

javascript - 文本区域值从选择选项值开始不断递增

html - 使用列计数和边框样式不能一起使用

css - 使用子选择器的菜单 css

javascript - 当我尝试使用 jquery.PrintElement.js 打印页面时,我得到 "access is denied"

jquery - 滚动时重新计算 Canvas 高度

javascript - tablesorter() 用于 dd-MMM-yyyy 格式的 jQuery 函数

javascript - 页面完全加载后如何更改html内容

javascript - 无法更改图像的位置

html - 如何在插入英雄图像顶部的图像下插入标题