代码之家  ›  专栏  ›  技术社区  ›  Willem van der Veen

数据-*HTML5中的属性

  •  1
  • Willem van der Veen  · 技术社区  · 7 年前

    正在阅读 an article on Mozilla 关于数据属性。文章说您可以使用data-*属性来存储关于元素的额外信息。例如:

    <article
      id="electriccars"
      data-columns="3"
      data-index-number="12314"
      data-parent="cars">
    ...
    </article>
    

    问题:

    它们的唯一目的是向HTML元素添加自定义元数据,还是有其他用例?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Joel    7 年前

    如何创建和使用以角度为框架的自定义属性的示例(演示用例)

    HTML:

    <button id="monitorBtn-{{machine.id}}" class="btn btn-success machine-action-btn"
                    ng-class="{'activeBtn': machine.isMonitored, 'btn-disabled': !$ctrl.hasValidMachineConfigAndBatch(machine)}"
                    ng-click="$ctrl.monitorClick(machine);"
                    ng-disabled="!$ctrl.hasValidMachineConfigAndBatch(machine)">
         <span ng-show="!$ctrl.isMonitored(machine)">
                    StackOverFlow
         </span>
    </button>
    

    JS:

    hasValidMachineConfigAndBatch(machine: Machine): boolean {
        var element = angular.element("#monitorBtn-"+machine.id);
        if (_.isNil(machine.currentMachineConfig) || _.isNil(machine.currentBatch)){
            element.attr("tooltip","Your Tooltip Text");
            element.attr("flow","up");
            console.log(element);
            return false;
        }
        element.removeAttr("tooltip");
        element.removeAttr("flow"); 
        return true;
    }
    

    这将向button类附加一个属性,如下所示:

    <button id="monitorBtn-{{machine.id}}" tooltip="Your tooltip Text" flow="up" ....>
    

    当然:这个自定义类是用 CSS4 .

    CSS:

    :root {
        --bg: #05a8ff;
        --alt: #ad4375;
        --text: #fff;
        --opacity: 1;
        --accent: #8fd1f2;
        --shadow: rgba(0, 0, 0, 0.35);
        --dink: 7px;
        --ani: 150ms cubic-bezier(0.5, 0, 0.6, 1.3) 1ms forwards;
    }
    
    [tooltip] {
        position: relative;
    }
    [tooltip]:not([flow])::after,
    [tooltip][flow^="up"]::after {
        bottom: calc(100% + var(--dink));
    }
    

    这决不是问题的答案,我认为这个问题没有真正的答案。它非常广泛,但我将发布这段代码,让您了解数据的用例,*attrs如何在不同的语言中工作,以及为什么HTML支持它们。

    推荐文章