用于显示onclick事件计数的可调整跨度标记

Adjustable span tag for showing onclick event count

本文关键字:可调整 显示 onclick 事件 用于      更新时间:2023-09-26

我目前有一个span标记,它显示按钮的onclick计数。现在,如果数字超过三位数,它将不适合范围标记。我可以调整跨度标签吗?还是可以调整其宽度,使其始终包含onclick计数?

我可以更改宽度以容纳更多的数字,但我希望它是可调整的,因为我无法预测实际会发生多少onclick事件。

var counts = {
  'Apples': 0,
  'Oranges': 0,
  'total': 0
};
   function countFruit(type) {
   document.getElementById('fruitCount').innerHTML = ++counts['total'];
   document.getElementById(type + 'Count').innerHTML = ++counts[type];
}

#OrangesCount{
z-index: 20;
position:absolute;
top:70px;
left:45%;
background-color:black;
width:80px;
border:2px solid green;
font-family: 'BPdotsUnicaseSquareBold';
font-size:25px;
color:yellow;
padding-right:4px;
padding-left:4px;
 }

#ApplesCount{
z-index: 20;
position:absolute;
color:yellow;
top:70px;
right:45%;
background-color:black;
width:80px;
border:2px solid green;
font-family: 'BPdotsUnicaseSquareBold';
font-size:25px;
   }
   <a id="buttonright" href="#" onclick="countFruit('Apples'); return false;">
   <a id="buttonleft" href="#" onclick="countFruit('Oranges'); return false;">
   <span id="ApplesCount"></span>
   <span id="OrangesCount"></span>

您只需要从两个css中删除width

#ApplesCount{
    z-index: 20;
    position:absolute;
    color:yellow;
    top:70px;
    right:45%;
    background-color:black;
    border:2px solid #550010;
    font-family: 'BPdotsUnicaseSquareBold';
    font-size:25px;
}

这是JSFiddle

如果需要允许元素自动调整其宽度,请不要固定其宽度。您可以指定最小宽度,就像下面的CSS示例一样。

#OrangesCount{
z-index: 20;
position:absolute;
top:70px;
left:45%;
background-color:black;
/*removed
width:80px;
*/
min-width:80px;
border:2px solid #001855;
font-family: 'BPdotsUnicaseSquareBold';
font-size:25px;
color:yellow;
padding-right:4px;
padding-left:4px;
}

#ApplesCount{
z-index: 20;
position:absolute;
color:yellow;
top:70px;
right:45%;
background-color:black;
/*removed
width:80px;
*/
min-width:80px;
border:2px solid #550010;
font-family: 'BPdotsUnicaseSquareBold';
font-size:25px;
}