Подтвердить что ты не робот

Темы пользовательского интерфейса jQuery и таблицы HTML

Есть ли способ использовать HTML-таблицу (CSS) для использования тем CSS-темы jQuery?

Все мои компоненты выглядят так, как будто они принадлежат друг другу, за исключением моей таблицы HTML, которая выглядит по-другому.

4b9b3361

Ответ 1

Там есть множество ресурсов:

Плагины с поддержкой ThemeRoller:

jqGrid

DataTables.net

UPDATE: вот что я собрал, чтобы стиль таблицы:

<script type="text/javascript">

    (function ($) {
        $.fn.styleTable = function (options) {
            var defaults = {
                css: 'styleTable'
            };
            options = $.extend(defaults, options);

            return this.each(function () {

                input = $(this);
                input.addClass(options.css);

                input.find("tr").live('mouseover mouseout', function (event) {
                    if (event.type == 'mouseover') {
                        $(this).children("td").addClass("ui-state-hover");
                    } else {
                        $(this).children("td").removeClass("ui-state-hover");
                    }
                });

                input.find("th").addClass("ui-state-default");
                input.find("td").addClass("ui-widget-content");

                input.find("tr").each(function () {
                    $(this).children("td:not(:first)").addClass("first");
                    $(this).children("th:not(:first)").addClass("first");
                });
            });
        };
    })(jQuery);

    $(document).ready(function () {
        $("#Table1").styleTable();
    });

</script>

<table id="Table1" class="full">
    <tr>
        <th>one</th>
        <th>two</th>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
    </tr>
</table>

CSS:

.styleTable { border-collapse: separate; }
.styleTable TD { font-weight: normal !important; padding: .4em; border-top-width: 0px !important; }
.styleTable TH { text-align: center; padding: .8em .4em; }
.styleTable TD.first, .styleTable TH.first { border-left-width: 0px !important; }

Ответ 2

dochoffiday answer - отличная отправная точка, но для меня это не сократило (часть CSS нуждалась в баффе), поэтому я сделал модифицированную версию с несколькими улучшениями.

Посмотрите в действии, затем верните описание.

JavaScript

(function ($) {
    $.fn.styleTable = function (options) {
        var defaults = {
            css: 'ui-styled-table'
        };
        options = $.extend(defaults, options);

        return this.each(function () {
            $this = $(this);
            $this.addClass(options.css);

            $this.on('mouseover mouseout', 'tbody tr', function (event) {
                $(this).children().toggleClass("ui-state-hover",
                                               event.type == 'mouseover');
            });

            $this.find("th").addClass("ui-state-default");
            $this.find("td").addClass("ui-widget-content");
            $this.find("tr:last-child").addClass("last-child");
        });
    };
})(jQuery);

Различия с исходной версией:

  • класс CSS по умолчанию был изменен на ui-styled-table (он звучит более согласованно)
  • вызов .live был заменен рекомендуемым .on для jQuery 1.7 вверх
  • явное условие заменено на .toggleClass (эквивалент терминов)
  • код, который устанавливает ошибочно названный CSS-класс first в ячейках таблицы, был удален
  • код, который динамически добавляет .last-child к последней строке таблицы, необходим для исправления визуального сбоя в Internet Explorer 7 и Internet Explorer 8; для браузеров, поддерживающих :last-child не нужно

CSS

/* Internet Explorer 7: setting "separate" results in bad visuals; all other browsers work fine with either value. */
/* If set to "separate", then this rule is also needed to prevent double vertical borders on hover:
table.ui-styled-table tr * + th, table.ui-styled-table tr * + td  { border-left-width: 0px !important; } */
table.ui-styled-table { border-collapse: collapse; }

/* Undo the "bolding" that jQuery UI theme may cause on hovered elements
/* Internet Explorer 7: does not support "inherit", so use a MS proprietary expression along with an Internet Explorer <= 7 targeting hack
        to make the visuals consistent across all supported browsers */
table.ui-styled-table td.ui-state-hover {
    font-weight: inherit;
    *font-weight: expression(this.parentNode.currentStyle['fontWeight']);
}

/* Initally remove bottom border for all cells. */
table.ui-styled-table th, table.ui-styled-table td { border-bottom-width: 0px !important; }

/* Hovered-row cells should show bottom border (will be highlighted) */
table.ui-styled-table tbody tr:hover th,
table.ui-styled-table tbody tr:hover td
{ border-bottom-width: 1px !important; }

/* Remove top border if the above row is being hovered to prevent double horizontal borders. */
table.ui-styled-table tbody tr:hover + tr th,
table.ui-styled-table tbody tr:hover + tr td
{ border-top-width: 0px !important; }

/* Last-row cells should always show bottom border (not necessarily highlighted if not hovered). */
/* Internet Explorer 7, Internet Explorer 8: selector dependent on CSS classes because of no support for :last-child */
table.ui-styled-table tbody tr.last-child th,
table.ui-styled-table tbody tr.last-child td
{ border-bottom-width: 1px !important; }

/* Last-row cells should always show bottom border (not necessarily highlighted if not hovered). */
/* Internet Explorer 8 BUG: if these (unsupported) selectors are added to a rule, other selectors for that rule will stop working as well! */
/* Internet Explorer 9 and later, Firefox, Chrome: make sure the visuals are working even without the CSS classes crutch. */
table.ui-styled-table tbody tr:last-child th,
table.ui-styled-table tbody tr:last-child td
{ border-bottom-width: 1px !important; }

Примечания

Я тестировал это в Internet Explorer 7 и выше, Firefox 11 и Google Chrome 18 и подтвердил, что он работает отлично. Я не тестировал достаточно ранние версии Firefox и Chrome или любую версию Opera; однако эти браузеры хорошо известны хорошей поддержкой CSS, и, поскольку мы не используем никаких функциональных возможностей с кровотечением, я предполагаю, что он будет работать и там очень хорошо.

Если вы не заинтересованы в поддержке Internet Explorer 7, есть один атрибут CSS (введенный с помощью взлома звезды), который может пойти.

Если вы не заинтересованы в поддержке Internet Explorer 8, CSS и JavaScript, связанные с добавлением и таргетингом на класс last-child CSS, могут также работать.

Ответ 3

Почему noy просто использует стили темы в таблице? то есть.

<table>
  <thead class="ui-widget-header">
    <tr>
      <th>Id</th>
      <th>Description</th>
    </td>
  </thead>
  <tbody class="ui-widget-content">
    <tr>
      <td>...</td>
      <td>...</td>
    </tr>
      .
      .
      .
  </tbody>
</table>

И вам не нужно использовать какой-либо код...