Jquery:获取包含最多字符/最长的H2的宽度
我正在尝试选择包含最多字符的 H2,或者宽度最宽的 H2,无论哪一个更简单,或者如果您知道如何做到这一点,您可以同时放置两者吗?我不确定语法。
I'm trying to select the H2 that contains the most characters, or is the widest in width, whichever one is simpler, or if you know how to do it could you put both? I'm not sure of the syntax.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要获得最宽的像素,您可以通过滥用
.width()
函数,例如:您可以在此处测试。在这个函数中,
w
是当前宽度,所以我们只是看看它是否比我们当前最宽的宽度更宽,如果是,则将当前宽度设置为新的最宽和最宽
更改为比之前最宽的当前。
您可以使用
.text()
对字符计数执行类似的操作:< a href="http://jsfiddle.net/nick_craver/zAGLP/1/" rel="nofollow">您可以在此处测试该版本。
To get the pixel-widest, you could just loop though kind of abusing the
.width()
function, for example:You can test it out here. Inside this function
w
is the current width, so we're just seeing if it's wider than our current widest, and if so setting the current width to the new widest andwidest
to the current<h2>
that was found to be wider than the previous widest.You can do something similar for character count using
.text()
:You can test that version here.
它们都非常相似,您必须遍历每一个并检查每个长度或宽度。 您可以用
$(element).width()
替换$(element).text().length
并适当地重命名变量。请注意,如果 2 个元素具有完全相同的宽度,则只会选择第一个元素。
They're both pretty similar, you'll have to iterate through each one and check for each length or width. Something like
You can substitute
$(element).width()
for$(element).text().length
and rename vars appropriately.Note that if 2 elements have the exact same width, this will only select the first one.