HTML5中的data- *属性

时间:2018-07-20 07:43:02

标签: html html5

正在阅读an article on Mozilla有关数据属性的信息。本文说,您可以使用data- *属性存储有关该元素的其他信息。例如:

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

问题:

将自定义元数据添加到HTML元素的唯一目的还是还有其他用例?

1 个答案:

答案 0 :(得分:2)

有关如何使用Angular作为框架来创建和使用自定义属性的示例(演示用例)

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 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));
}

这绝不是问题的答案,而且我认为对此问题没有真正的答案。它非常广泛,但是我将发布此代码,以使您了解data- * attrs如何在不同语言中工作的用例,以及为什么HTML会采用它们。