gpt4 book ai didi

javascript - 如何使按钮宽度跟随基于文本的最大宽度按钮?

转载 作者:行者123 更新时间:2023-12-01 06:21:37 25 4
gpt4 key购买 nike

如何使所有按钮都遵循基于文本的较大宽度的宽度?

按钮动态生成,文本将基于数据库中的数据。然后我希望它们在 UI 上具有相同的大小。

这可能吗?如果是。怎么办?

这是我的按钮:

@foreach($buttons as $button)
<button class="btn col-lg-2 col-md-3 col-sm-4 text-center btn-button button{{$button->parent_id}} hide" type="button" onclick="buttonFunction('button{{$button->id}}'" style="background-color: #69C1DA;">
<input type="radio" class="hide" name="type" value="{{$button->id}}" id="button{{$button->id}}">
<span>{{$button->name}}</span>
</button>
@endforeach

这是我的按钮的用户界面

enter image description here

如您所见,文本未安装。我可以使按钮比现在更大,但我不知道数据库中的单词什么时候会变得足够大而不再适合。

提前致谢。

最佳答案

如果是我 - 我会忘记尝试使用 boostrap 列,而只是使用 css 设置宽度样式。

这可以用普通的 javascript 完成(特别是使用 document.querySelectorAll() 选择器 - 但由于您使用的是 jquery - 这是方法 -

迭代按钮并通过将每个按钮宽度与最大宽度进行比较来找到最大宽度,如果它大于最大宽度 - 将该宽度设置为最大宽度。

然后将所有按钮设置为 maxWidth,瞧 - 所有按钮的宽度都与具有最长文本的按钮相同。

请注意,我只是为此代码段删除了一些代码 - 并且还将样式移到了 css block 中 - 对于每个按钮使用外部 css 总是比使用内联更好。如果您想为不同的按钮使用不同的样式 - 应用具有不同样式的不同类。

let maxWidth = 0;

$('.btn').each(function(){
const width = parseFloat($(this).css('width'));
if(width > maxWidth) {maxWidth = width}
})

$('.btn').css('width', maxWidth +'px');
.btn {
background-color: #69C1DA;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn text-center btn-button button{{$button->parent_id}} hide" type="button">

<span>text</span>
</button>
<button class="btn text-center btn-button button{{$button->parent_id}} hide" type="button">
<span>longer text</span>
</button>
<button class="btn text-center btn-button button{{$button->parent_id}} hide" type="button" onclick="buttonFunction('button{{$button->id}}'">
<span> very very long text</span>
</button>
<button class="btn text-center btn-button button{{$button->parent_id}} hide" type="button">
<span>short text</span>
</button>

关于javascript - 如何使按钮宽度跟随基于文本的最大宽度按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60218810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com