【问题标题】:Customisation search form (as on stackoverflow) with javascript使用 javascript 自定义搜索表单(如在 stackoverflow 上)
【发布时间】:2012-02-26 05:10:03
【问题描述】:

您好,亲爱的 stackoverflow 用户!

我真的很喜欢这个网站上的搜索表单,当用户开始输入字符时,它会被拉伸。我试图自己理解脚本,但我的知识不足以达到这个目的。据我了解,它是使用 jquery 实现的。而且我很好奇 - 有没有这种实现的演示示例(作为 jquery 框架站点的一个选项)? 提前感谢您的帮助!

【问题讨论】:

    标签: javascript jquery input field


    【解决方案1】:

    使用 HTML 表单,您可以使用 jQuery 为字段设置动画。

    我在下面创建了一个基本表单和简单的 jQuery 脚本。至于实际处理搜索,您需要另一个页面来提交表单并实际执行搜索。


    HTML ——创建表单和搜索字段。

    <form action='search.php' method='POST'>
    <input type='search' name='searchQuery' id='inputSearch' placeholder='Search the site'>
    </form>
    

    jQuery — 检查 keypress(),如果该字段尚未展开:将其设置为更大的动画并设置一个变量以阻止其重复动画。使用 blur() 检查字段是否失焦,将字段设置为正常大小并设置一个变量以指示字段可以再次展开。

    var isExpanded = false;
    
    $(document).ready(function () {
        $('#inputSearch').keypress(function () {
            if (isExpanded == false) {
                $(this).animate({width: 500}, 'slow');
                isExpanded = true;
            }
        });
    
        $('#inputSearch').blur(function () {
            $(this).animate({width: 150}, 'slow');
            isExpanded = false;
        });
    });
    

    【讨论】:

    • 你给了我难以置信的支持。我不知道该怎么感谢你。请接受我真诚的感谢!顺便说一句,请原谅我蹩脚的英语——它不是母语;)
    【解决方案2】:

    我会这样做:

    var expandedWidth = "350px",
        width = "200px";
    
    //Expand the input el when user types first character
    $("#input").keypress(function(){
        width = this.style.width;
        if(width !== expandedWidth){
            this.style.width = expandedWidth;
        }
    });
    
    //Set it back to the default/initial width when it loses focus
    $("#input").blur(function(){
        this.style.width = width;
    });
    

    example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多