jQuery-在选择列表中获取选项的像素宽度? [英] jQuery - get pixel width of option in a select list?

查看:38
本文介绍了jQuery-在选择列表中获取选项的像素宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过以下内容,我可以得到选择输入的宽度(以像素为单位).是否可以在选择列表中获得选项的宽度?谢谢

With the following I can get the width of a select input in pixels. Is it possible to get the width of an option within the select list? Thanks

$('#mySelect').width();

更新-这是我想要这个的原因.我需要在选择列表中将文本居中.我不能使用CSS text-align:center;跨设备和浏览器.我唯一的选择是使用text-indent.由于我的网站具有液体宽度,并且选项的长度不同,因此我需要动态计算此值.

UPDATE - heres the reason I want this. I need to center text in a select list. I cant do this cross device and browser with css text-align: center; My only option is to use text-indent. As my site has a liquid width and the options are of different lengths, I need to calculate this value dynamically.

因此,如果我可以获取选择选项文本的宽度,并且还可以获取容器的宽度(容易得多),那么我可以计算出文本缩进应该是什么.谢谢

So, if I could get the width of the select option text, and also get the width of the container (much easier), then I could calculate what the text-indent should be. Thanks

NimChimpsky的方法似乎可以正常工作.代码在这里: jQuery-在div点击时触发功能运行正常,但在页面加载时未运行

NimChimpsky's method seems to work fine. Code is here: jQuery - function runs fine when fired on div click, but not on page load

推荐答案

您可以像这样获得所选选项的字符串长度:

you can get string length of selected option like so :

 ("#mySelect option:selected").text().length

并针对特定的索引元素(此处为2)执行此操作:

and for a specific index element (2 here) do this :

$("#mySelect option[value='2']").text().length

或者,您可以将选定的文本放入不可见的div中,然后使用常规的jQuery宽度方法获得该div的宽度.

Alternatively you could take the selected text, put it in an invisible div, then get the width of that div - using normal jquery width method.

这篇关于jQuery-在选择列表中获取选项的像素宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆