【问题标题】:Best way to handle spaces in formatting while cloning in jQuery?在 jQuery 中克隆时处理格式中空格的最佳方法?
【发布时间】:2014-01-11 19:46:10
【问题描述】:

所以我有一些 jQuery 在这里工作:http://jsfiddle.net/8VtZf/

这是它在开始时的样子......有(1)和(2),当我点击添加按钮时,它将克隆最后一个,并增加数字。这一切正常,信息开头为:

<div class="inputClones">
    <input class="inputButton" type="button" name="result[]" value="1" />
    <input class="inputButton" type="button" name="result[]" value="2" />
</div>

当我单击克隆按钮时出现问题。克隆会发生在元素上,但不会保留格式...结果代码如下:

<div class="inputClones">
    <input class="inputButton" type="button" name="result[]" value="1" />
    <input class="inputButton" type="button" name="result[]" value="2" /><input class="inputButton" type="button" name="result[]" value="3" /><input class="inputButton" type="button" name="result[]" value="4" />
</div>

因此,(1) 和 (2) 之间的固有间距将在添加的克隆之间丢失。添加这个额外间距的最佳方法是什么?

【问题讨论】:

  • 你应该使用 CSS。不同的浏览器有不同的内置样式表。

标签: jquery html clone


【解决方案1】:

您可以使用的一个技巧是将父元素的 font-size 设置为 0。这是因为奇数间距是由后续 input 元素之间缺少空格字符引起的。

.inputClones {
    font-size: 0;
}

Here's a working fiddle for the above.

如果您想自定义按钮之间的间距,只需在 inputButtons 中添加一个 margin-right。

.inputButton {
    margin-right: 8px;
}

Working fiddle with custom button spacing.

如果您希望保留实际的空格字符,那么我认为您不走运。

【讨论】:

  • 但是如果我想要空间呢?
  • @JasonAxelrod 然后检查我的答案。保证一致性的唯一方法。
【解决方案2】:

依赖浏览器来设置样式和布局元素是个坏主意。你最好为按钮定义一些 CSS:

.inputClones input[type="button"] {
    float: left;
    margin-right: 10px;
}
    .inputClones input[type="button"]:last-child {
        margin-right: 0;
    }

jsFiddle Demo

【讨论】:

    【解决方案3】:

    在css中添加固定边距

    css:

    .inputButton  {  
    margin-right:1%
    }
    

    HTML:

    <div class="inputClones">
        <input class="inputButton" type="button" name="result[]" value="1" /><input class="inputButton" type="button" name="result[]" value="2" />
    </div>
    <br />
    <input type="button" value="Add Button" class="addButton">
    

    jquery 没有任何修改 DEMO

    【讨论】:

    • CSS 不是解决方案...因为它在第一个元素中仍然有额外的空间...基本上右边的边距变为 margin-right: 1%...加上额外的空间.它不是恒定的。
    • 我提供的 html 存在 no 问题 ;) 特别为您添加了演示
    猜你喜欢
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    • 2011-09-24
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多