简体   繁体   English

动态设置文本宽度

[英]Setting the text width on dynamically

I have created a tab component, the one part which I am not able to achieve is that, instead of TabIndicator to entirely take the length of the tab container I need to set only the text width.我创建了一个选项卡组件,我无法实现的一个部分是,而不是 TabIndicator 完全占用选项卡容器的长度,我只需要设置文本宽度。

Since each text has different width I am using js to calculate it, but instead of getting the width, I am able to get the container width.由于每个文本都有不同的宽度,我使用 js 来计算它,但不是获取宽度,而是获取容器宽度。

How can I make the active TabIndicator line only expand from the start of the text to the end of text.如何使活动的 TabIndicator 行仅从文本开头扩展到文本结尾。

I am able to achieve the container width.我能够实现容器宽度。 Adding the sandbox link for the same.为其添加沙盒链接。

Sandbox沙盒

It's simple.这很简单。 You need to subtract extra paddings while calculating the start and width of the indicator.在计算指标的开始和宽度时,您需要减去额外的填充。
.tab has 6px padding horizontally .tab 有 6px 水平填充
.tab-default-container has 1rem padding on desktop it's 16px .tab-default-container 在桌面上有 1rem 填充,它是 16px
. . So change code something like:所以更改代码如下:

if (tabMeta && tabsMeta) {
 startValue = tabMeta.left - tabsMeta.left + tabsMeta.scrollLeft + 22; //16+6=22
}

//22 from both sides = 44px tor remove.
const newIndicatorStyle = {
   left: startValue,
   width: tabMeta ? tabMeta.width - 44 : 0
};

Updated sandbox .更新沙盒
Note: You've used relative unit rem it may evaluate different on different settings and devices, it may not be 1rem=16px.注意:您使用了相对单位rem ,它可能在不同的设置和设备上评估不同,它可能不是 1rem=16px。

The rem (for “root em”) is the font size of the root element of the document. rem(代表“root em”)是文档根元素的字体大小。

So do the calculations considering this.考虑到这一点,请进行计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM