CSS标签:内容样式之前无法使用,除非为元素提供了ID

问题描述 投票:0回答:1

我建立了一个可点击的am / pm按钮,它是时间选择器的一部分。它将位于动态表(html表,用户可以在其中单击按钮以向表中添加行)内。由于它位于动态表中,因此我将生成元素,并且尝试在javascript中访问元素ID时不会过多使用(因为我不会单独知道它们)。

使用下面的可点击标签,是否有任何方法可以在不为复选框分配ID的情况下达到相同的结果?

.text_toggle
{
    display: none;
}

.text_toggle + label
{
    position: relative;
    cursor: pointer;
    color: #aaa;
}

.text_toggle + label:hover
{
    color: blue;
}

.text_toggle:not(:checked) + label:before
{
    content: attr(data-off);
    position: absolute;
}

.text_toggle:checked + label:before
{
    content: attr(data-on);
    position: absolute;
}
<input id="am_pm" class="text_toggle" type="checkbox" checked>
                <label for="am_pm" data-off="am" data-on="pm"></label>
javascript html css dom
1个回答
0
投票

是,您可以制作一个标签并将其复选框放入其中,然后添加具有自定义属性的另一个元素。

.switch{
/* other styles here */
}
.switch > input[type=checkbox]{
display:none;
}

.switch input[type=checkbox] + span::before{
  content: attr(data-off)
}
.switch input[type=checkbox]:checked + span::before{
content: attr(data-on)
}
<label class="switch">
<input type="checkbox" />
<span data-off="Off" data-on="On"></span> <!-- I made it with span, but feel free to use any other tag -->
</label>
© www.soinside.com 2019 - 2024. All rights reserved.