如何在输入标签内显示div?

我正在尝试为我的网站创建像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

简答:你不能/不能。 但你可以给出你的样子。

更长的回答: 例子

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

您不能在输入标记中插入div。 在stackoverflow中,如果您尝试在输入标记中添加标记,然后右键单击输入标记然后单击Inspect Element,您将看到它们正在添加span标记,但不在输入标记本身内。

 
//for the tags
 $(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(""+valueofinput+" "); $('.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/