【问题标题】:How to display div inside input tag?如何在输入标签内显示 div?
【发布时间】:2013-07-30 02:15:59
【问题描述】:

我正在尝试为我的网站创建像 stackoverflow 这样的标签,我网站上的用户将创建标签来过滤结果或许多其他操作,如搜索、专业知识等。

我可以创建标签,但不能像在 stackoverflow 中那样在输入框中显示它,标签之间的边距存在问题。每次我创建标签时,它都是对齐的,但没有空格或边距。 目前它正在显示所有内联标签,没有任何空格。

我试过的jQuery-

$(function () {        
    $("#inputtext").keypress(function (e) {
        var valueofinput = $(this).val();
        if (e.which == 13) {
            $('.tag').html(valueofinput);
            $('.tag').show();
        }
    });

    $('.tag').click(function () {
        $(this).hide();
    });        
});    

但是我尝试在这样的输入标签中显示它-

if(e.which==13)
{
$("#inputtext").val().addClass('tag').css('display','inline-block');
}
if(e.which==32)     //for space
{
$('.tag').css('margin-left','5px');
}

但这不起作用。

Jsfiddle

【问题讨论】:

  • $("#inputtext").val() 是一个 getter 方法,请尝试改用 $("#inputtext").val('').addClass('tag').css('display','inline-block');
  • 也许使用 Tagit 插件?

标签: javascript jquery css


【解决方案1】:

简短回答:您不能/不可以。但是你可以表现出你的样子。

更长的答案:Example

$(function(){    
    $("#inputtext").keypress(function(e){
        var valueofinput= $(this).val();
        if(e.which==13)
        {
            $('#inputtext').before('<span class="tag">' + valueofinput + '</span>');
            $('input').val('');
        }
    });
    $(document).on('click', '.tag', function(){
        $(this).remove();
    });
    $('.inputholder').click(function() { $('#inputtext').focus(); });
});

【讨论】:

  • 感谢您的回答,它很有帮助,但现在我无法在点击时删除标签。
  • 已修复。对不起,我第一次错过了。
  • 绑定是$('.tag').click(),但是,我们之后使用tag类创建了更多元素,因此绑定不适用,因为它们在绑定时必须在DOM中事件。所以我将事件监听器改为查看document
【解决方案2】:

您不能在输入标签中插入 div。在stackoverflow中,如果您尝试在输入标签中添加标签,然后右键单击输入标签,然后单击检查元素,您将看到他们正在添加跨度标签,但不在输入标签本身内。

<div>
   <span >  //for the tags
  <input />
</div>

【讨论】:

    【解决方案3】:
    $(function(){
     var oldVal;         
     $("#inputtext").change(function(e){    
           oldVal= $(this).val();    
     });   
    
     $("#inputtext").keypress(function(e){        
        var valueofinput= $(this).val().replace(oldVal,'');
         if(e.which==13)
        {
            $('.tag').append("<span>"+valueofinput+"</span>&nbsp;");         
            $('.tag').show();
        }        
     });    
    });
    

    css

    .tag
    {
     height:auto;
     width:auto;
     background:white;
     color:white;
     text-align:center;
     display:none;
     position:absolute;
     padding:5px;    
     margin:1em;
    }
    
    .tag > span
    {
      background:green;
    }
    

    http://jsfiddle.net/Hb8yj/14/

    【讨论】:

      猜你喜欢
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-10
      • 2011-05-26
      • 2016-07-11
      • 2017-11-01
      • 2019-11-07
      相关资源
      最近更新 更多