jQuery按钮附加空间问题

时间:2014-06-05 12:43:32

标签: jquery html css

我使用jQuery追加方法追加按钮。

$('#btnContainer').on('click', '.btn', function(){

    var test  = $('<input>', {
                    type: 'button',  // Set type of input element                  
                    class: 'btn', // Applies class btn
                    value: 'Button', //sets value of Button
                    click: function () { }
                });

    $("#btnContainer").append(test);    

});

在追加后,无法理解第一个按钮右侧空间比其他空间更多。 我也没有申请任何其他的CSS。 (更多信息见图片) enter image description here

CODE: http://jsfiddle.net/ajaypatel_aj/XCsNu/

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<style type="text/css">
.btn{
    color: #000000;
    font-size: 11px;
    line-height: 1.2;![enter image description here][2]
    white-space:nowrap;
}
</style>

</head>

<body>
<div id="btnContainer">
    <input type="button" class="btn" value="Button" />
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script language="javascript" type="application/javascript">

$('#btnContainer').on('click', '.btn', function(){

    var test  = $('<input/>', {
                    type: 'button',  // Set type of input element                  
                    class: 'btn', // Applies class btn
                    value: 'Button', //sets value of Button
                    click: function () { }
                });

    $("#btnContainer").append(test);    

});

</script>
</body>
</html>

2 个答案:

答案 0 :(得分:3)

修改此html

<div id="btnContainer">
    <input type="button" class="btn" value="Button" />
</div>

<div id="btnContainer"><input type="button" class="btn" value="Button" /></div>

div中的空格导致了这个问题。 演示:http://jsfiddle.net/XCsNu/2/

答案 1 :(得分:2)

这与原始按钮周围的空白有关。附加元素直接放在任何现有内容的末尾,因此不会出现此问题。因此,您可以通过在float: left;元素上设置.btn来强制缩小空白区域。

Updated fiddle