Jquery: Get the width of the H2 that contains the most characters/is longest
I'm trying to select the H2 that contains the most chara开发者_Python百科cters, 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.
To get the pixel-widest, you could just loop though kind of abusing the .width()
function, for example:
var cw = 0, widest;
$("h2").width(function(i, w) { if(w > cw) {widest = this; cw = w;} return w; });
//widest == widest h2 element
//$(widest).addClass("widest");
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 and widest
to the current <h2>
that was found to be wider than the previous widest.
You can do something similar for character count using .text()
:
var cw = 0, widest;
$("h2").text(function(i, t) { if(t.length > cw) {widest = this; cw = t.length;} return t; });
$(widest).addClass("widest");
You can test that version here.
They're both pretty similar, you'll have to iterate through each one and check for each length or width. Something like
var maxWidth = 0;
function getLongest(){
var elementWidth,
domNode;
$("h2").each(function(i, element){
elementWidth = $(element).width();
if (elementWidth > maxWidth){
domNode = element;
maxWidth = elementWidth;
}
}
return domNode;
}
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.
$(document).ready(function() {
var longestH2 = null;
$("h2").each(function(k, v) {
if ($(v).width() > $(longestH2).width() || longestH2 == null) longestH2 = v;
});
$(longestH2).css("border", "3px solid red");
});
精彩评论