Html 如何解决 Bootstrap 3 的表单控件类的需求?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18158293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 12:01:37  来源:igfitidea点击:

How can I work around the need for Bootstrap 3's form-control class?

csshtmlformstwitter-bootstraptwitter-bootstrap-3

提问by orokusaki

I decided to try out Bootstrap 3 tonight for the first time. I noticed that, in order to get the default, pretty form field styling, you need to add a form-controlclass to each input, textarea, select, etc. This is a pain for those who dynamically generate their forms (e.g., using Django). Django allows you to set attributes of form fields, but to do so globally would require a nasty monkey patch or else very non-DRY code.

我决定今晚第一次尝试 Bootstrap 3。我注意到,为了获得默认的、漂亮的表单字段样式,您需要为form-control每个 input、textarea、select 等添加一个类。这对于那些动态生成表单的人来说是一种痛苦(例如,使用 Django)。Django 允许您设置表单字段的属性,但要在全局范围内这样做将需要一个讨厌的猴子补丁或非常非 DRY 的代码。

  1. Is there a way to avoid the requirement of this class, still retaining the basic form field styles?
  2. Is there a quick way (preferably non-JS) to address this otherwise?
  1. 有没有办法避免这个类的要求,仍然保留基本的表单字段样式?
  2. 有没有一种快速的方法(最好是非 JS)来解决这个问题?

采纳答案by ornoone

You realy should check a Django app that render all your Django forms as nice Boostrap forms, simply by using a tag in your template.

您确实应该检查一个 Django 应用程序,该应用程序将您的所有 Django 表单呈现为漂亮的 Boostrap 表单,只需在您的模板中使用一个标签即可。

Its name is django-bootstrap3. Here's how you use it:

它的名字是django-bootstrap3。以下是您如何使用它:

  1. Install django-bootstrap3
  2. Add bootstrap3to your INSTALLED_APPS:

    INSTALLED_APPS = (
        ...
        'bootstrap3',
        ...
    )
    
  3. Update your template:

    1. load bootstrap3
    2. replace your {{form.as_p}}to {% bootstrap3_form form %}
  1. 安装 django-bootstrap3
  2. 添加bootstrap3到您的INSTALLED_APPS

    INSTALLED_APPS = (
        ...
        'bootstrap3',
        ...
    )
    
  3. 更新您的模板:

    1. 加载 bootstrap3
    2. 替换你{{form.as_p}}{% bootstrap3_form form %}

before:

前:

<form method="post" class="form-horizontal" action="" >
    <div class="hidden-desktop">
      <button type="submit" class="btn btn-primary"> Save</button>
    </div>
    {% csrf_token %}
    {{ form.as_p }}
    <div class="actions form-actions">
      <button type="submit" class="btn btn-primary"> Save</button>
    </div>
 </form>

after:

后:

{% extends "base.html" %} 
{% load bootstrap3 %}

<form method="post" class="form-horizontal" action="" >
  <div class="hidden-desktop">
    <button type="submit" class="btn btn-primary">{% bootstrap_icon "ok" %} Save</button>
  </div>
  {% csrf_token %}
  {% bootstrap_form form  %}
  <div class="actions form-actions">
    <button type="submit" class="btn btn-primary">{% bootstrap_icon "ok" %} Save</button>
  </div>

Nothing else to do. Nothing to update in you form. No JavaScript hacks.

没有别的事可做。在你的表格中没有什么要更新的。没有 JavaScript 黑客。

回答by Bass Jobsen

I wondered why the answer below got downvotes first. I found my answer about the form-groupin stead of the form-controlclass. The class form-controladds many CSS rules.

我想知道为什么下面的答案首先被否决了。我找到了关于 theform-group而不是form-control课堂的答案。该类form-control添加了许多 CSS 规则。

You should try to control your form output in the first place: https://stackoverflow.com/a/8474452/1596547

您应该首先尝试控制表单输出:https: //stackoverflow.com/a/8474452/1596547

If you can't you could try the same as below. Apply the same rules on your inputs instead of the form-control, like:

如果你不能,你可以尝试以下相同的方法。对您的输入应用相同的规则而不是form-control,例如:

input {
  display: block;
  width: 100%;
  height: 34px;
  padding: 6px 12px;
  font-size: 14px;
  line-height: 1.428571429;
  color: #555555;
  vertical-align: middle;
  background-color: #ffffff;
  border: 1px solid #cccccc;
  border-radius: 4px;
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  -webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
          transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
}

input:focus {
  border-color: #66afe9;
  outline: 0;
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(102, 175, 233, 0.6);
          box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(102, 175, 233, 0.6);
}

Less

较少的

With LESS > 1.4 you can use :extend(), see: https://stackoverflow.com/a/15573240/1596547. You can use this for the above by adding a rule to your less files:

随着 LESS > 1.4,您可以使用:extend(),请参阅:https: //stackoverflow.com/a/15573240/1596547。您可以通过向您的 less 文件添加规则来将其用于上述目的:

input {
  &:extend(.form-control all);
}

Also see: Why gives Grunt / Recess an error and Lessc not when compiling Bootstrap 3 RC1?

另请参阅:为什么在编译 Bootstrap 3 RC1 时会给 Grunt / Recess 一个错误而不会给 Lessc?

The form-groupis an container-div around your input / label constructs it only adds a margin-bottom: 15px;. You could build your forms without it. For this reason it is not required.

form-group是一个围绕您的输入/标签构造的容器 div,它只添加一个margin-bottom: 15px;. 没有它,你可以构建你的表单。出于这个原因,它不是必需的。

With css you could make some workarounds. I don't think you can avoid Javascript always. I don't know the HTML-structure of your Django forms. I have used the example form from http://getbootstrap.com/css/#formsand strip the form-controlcontainers. Then i "fix" the differences. NOTE i also add a <br>tag in front of the submit button.

See: http://bootply.com/73370

1) form-groupadds a margin-bottom: 15px;to fix this i add this margin to the input tags:

input {
    margin-bottom: 15px; }

This works accept for the checkbox (and radio). The Bootstrap CSS defines input[type="radio"], input[type="checkbox"] { line-height: normal; margin: 4px 0 0; }which overrules (caused by CSS Specificity, see: http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/) the css for input above.

So the final rule will be:

input, input[type="checkbox"]  {
    margin-bottom: 15px;
}

2) the label of the checkbox also differs. NOTE the checkbox don't have a surrounding form-controlbut a checkboxclass in stead. The css rules for the label text are: .radio label, .checkbox label { cursor: pointer; display: inline; font-weight: normal; margin-bottom: 0; }i this case you can't use CSS only (the label is a parent of the input checkbox, and there is no parent selector in CSS, see: Is there a CSS parent selector?). With jQuery you can select the label and add a class:

$('input[type="checkbox"]').parent("label").addClass('checkboxlabel');

Now add this class to your CSS with the same rules as the .checkbox label:

.checkboxlabel
{
    cursor: pointer;
    display: inline;
    font-weight: normal;
    margin-bottom: 0;
} 

Now both forms look basically the same i think:

使用 css,您可以做出一些解决方法。我认为你不能总是避免使用 Javascript。我不知道你的 Django 表单的 HTML 结构。我使用了http://getbootstrap.com/css/#forms 中的示例表单并剥离了form-control容器。然后我“修复”差异。注意我还在<br>提交按钮前添加了一个标签。

见:http: //bootply.com/73370

1)form-group添加一个margin-bottom: 15px;来解决这个问题,我将这个边距添加到输入标签中:

input {
    margin-bottom: 15px; }

这适用于复选框(和收音机)。Bootstrap CSS 定义了input[type="radio"], input[type="checkbox"] { line-height: normal; margin: 4px 0 0; }哪些覆盖(由 CSS 特异性引起,请参阅:http: //coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/)上面输入的 css。

所以最终的规则是:

input, input[type="checkbox"]  {
    margin-bottom: 15px;
}

2)复选框的标签也不同。注意复选框没有周围,form-control而是一个checkbox类。标签文本的 css 规则是:在.radio label, .checkbox label { cursor: pointer; display: inline; font-weight: normal; margin-bottom: 0; }这种情况下,您不能仅使用 CSS(标签是输入复选框的父级,并且 CSS 中没有父级选择器,请参阅:是否有 CSS 父级选择器?)。使用 jQuery,您可以选择标签并添加一个类:

$('input[type="checkbox"]').parent("label").addClass('checkboxlabel');

现在使用与以下相同的规则将此类添加到您的 CSS 中.checkbox label

.checkboxlabel
{
    cursor: pointer;
    display: inline;
    font-weight: normal;
    margin-bottom: 0;
} 

现在我认为这两种形式看起来基本相同:

forms look the sameAlso read: Django Forms and Bootstrap - CSS classes and <divs>

表格看起来一样另请阅读:Django Forms and Bootstrap - CSS classes and <divs>

回答by emperorcezar

One thing I did was create a mixin that adds the form-controlclass to each widget.

我做的一件事是创建一个 mixin,将form-control类添加到每个小部件。

class BootStrap3FormControlMixin(object):
    def __init__(self, *args, **kwargs):
        super(BootStrap3FormControlMixin, self).__init__(*args, **kwargs)

        for field in self.fields.values():
            _class = field.widget.attrs.get('class', '')
            field.widget.attrs.update({'class': u'%s %s' % (_class, 'form-control',)})