开发者

Select div with specific width

开发者 https://www.devze.com 2023-02-10 17:11 出处:网络
Quick Question: How to select a div with certain width. For example we have 10 div in one page, I want to select the one that has 200px width and do something.

Quick Question: How to select a div with certain width. For example we have 10 div in one page, I want to select the one that has 200px width and do something. Thanks开发者_运维百科 a lot.


What JCOC611 said:

var $theDivs = $('div').filter(function() { return $(this).width() === 200; });

That'd get you a jQuery object with all matching (200px) divs in it. Might not be the fastest thing in the world; it'd probably be better to more directly and explicitly identify your page elements, if you can.


You can also extend jQuery's pseudo-selectors, like this:

// Extend jQuery ":" pseudo selector to include a width() test

$.extend( $.expr[':'], {
    width: function ( element, index, selectorMatches ) {
        var expr = selectorMatches[3].match( /^\s*([<>]?={0,1})?\s*(\d+)\s*$/ ),
            elementWidth = $( element ).width(),
            targetWidth, comparisonOperator;

        if ( ! expr ){
            console.log( "invalid expression" );
            return false;
        }

        comparisonOperator = expr[1] || "==";
        targetWidth = parseInt( expr[2] );

        return eval( elementWidth + comparisonOperator + targetWidth );
    }
});


// Valid expressions are:
// :width( 200 ), :width( = 200 ), :width( == 200 )
// :width( > 200 ), :width( >= 200 )
// :width( < 200 ), :width( <= 200 )
$('div:width( 200 )').hide();

This IMHO is a lot more fun than using filter(), but jsperf shows it to be just a little bit slower (4% slower).

Here's a jsFiddle that you can play around with.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号