【问题标题】:How to add class/ID to any element?如何向任何元素添加类/ID?
【发布时间】:2012-01-06 03:07:11
【问题描述】:

我找不到简明的答案或帮助。我希望能够将类或 ID 添加到 Drupal 中的 ANY 元素。所以为了让页面上的按钮更容易,我想添加类“按钮”。这是如何以及在哪里完成的?我在 form.inc 中看到了一个参考,并使用了类似 module.php 的东西,但我正在努力获得一些具体的帮助。

【问题讨论】:

  • 这适用于什么版本的 Drupal?
  • Drupal 7.10。很抱歉没有把它说出来。

标签: html drupal dom drupal-7


【解决方案1】:

您需要为提供表单项标记的核心主题实现覆盖。其中包括theme_buttontheme_submittheme_textfield 以及其他加载项。

为此,请在活动主题的 template.php 文件中实现 MYTHEME_theme_name(),并根据需要覆盖输出:

function mytheme_button(&$variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'submit';
  element_set_attributes($element, array('id', 'name', 'value'));

  $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
  if (!empty($element['#attributes']['disabled'])) {
    $element['#attributes']['class'][] = 'form-button-disabled';
  }

  $element['#attributes']['class'][] = 'my-new-class';

  return '<input' . drupal_attributes($element['#attributes']) . ' />';
}

上面的函数是直接从theme_button()函数复制过来的,只是多加了一行,给按钮元素增加了一个额外的类。

确保在实现挂钩后清除 Drupal 的缓存,以便主题注册表将其拾取。

值得注意的是,Drupal 已经为单个元素添加了诸如 form-textform-submit 等类,因此如果您尝试使用 CSS 定位元素,则可以尝试使用这些类。

【讨论】:

  • 哇。是的,我的力量还没有那么强。我正在尝试使用 twitter/bootstrap CSS,所以我认为它会“相对”容易做到。我会乱来,看看我能走多远。
【解决方案2】:

这取决于您要更改的元素。
例如,您可以使用 hook_form_alter 将类和 id 添加到表单中。
其他元素必须在您的自定义主题模板中进行更改或否决,具体取决于元素出现的位置,例如html.tpl.php、page.tpl.php、block.tpl.php、node.tpl.php等等。
使用 DevelDevel themer 模块,您可以更好地了解查看位置。

编辑:顺便说一句,永远不要侵入核心,这会给你以后带来很多麻烦!

【讨论】:

    【解决方案3】:

    通过sites/all/themes/yourthemes/... 中的page.tpl.php,您可以随意输入id 或类名。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-11
      • 1970-01-01
      • 2013-08-03
      • 2011-12-26
      • 1970-01-01
      • 1970-01-01
      • 2015-08-27
      • 2016-06-09
      相关资源
      最近更新 更多