2009-10-26 2 views
15

jQuery에 스타일 선택기가 있습니까?

width 그러나 width CSS 속성 (예 : 단일 선택기)이 750x 인 모든 요소를 ​​선택하려면 어떻게해야합니까? ?

EDIT : 그런 셀렉터가 없다면 플러그인이 있습니까, 아니면 다음 jQuery 버전에서 수행 할 계획입니까?

+0

해당 선택자가 없습니다. –

답변

17

하지좋은 생각,하지만 당신은 그것을 위해 새로운 지글 지글 선택기를 추가 할 수 있습니다 : 당신이 다음과 같이 사용할 수

$.expr[':'].width = function(elem, pos, match) { 
    return $(elem).width() == parseInt(match[3]); 
} 

가 : 무슨

$('div:width(970)') 

가 엄청 시리 느린 하지만 다음 요소와 비교할 요소의 수를 좁히기를 원합니다.

$('#navbar>div:width(970)') 

은 너비가 970px 인 탐색 바의 직계 하위 항목 인 div 만 선택합니다.

+1

'$ .expr'은 jQuery에서 올바른 API입니까? Sizzle이 전역 범위에 노출되어 있기 때문에'jQuery.find.selectors.filters'를 사용했습니다. – eyelidlessness

+0

내 답변을 삭제 했으므로 다소 중복되었습니다. API에 대해서는 여전히 불분명하다. – eyelidlessness

+1

아. 그들은 같은 객체로 평가하지만, jQuery.find.selectors.filters는 훨씬 어리석은 것으로 보인다. 그것을 지적 해 주셔서 감사합니다 –

15
var $images = $("img").filter(function() { 
    return $(this).css('width') == '750px'; 
}); 

편집 : 알고있는 플러그인 또는 그러한 특정 기능을 포함하려는 계획이 없습니다. 당신은 쉽게 (안된)으로, 스스로를 pluginify 수 있습니다

$.fn.filterByWidth = function(width) { 
    var $images = $("img").filter(function() { 
     return $(this).css('width') == width; 
    }); 
    return $images; 
}; 

사용법 :

$images = $('#div img').filterByWidth('750px'); 
$images = $('#div img').filterByWidth('50%'); 
...etc... 
+1

하나의 간단한 선택기로 가능하지 않습니까? –

+0

대신 @ width를 사용해야합니다. –

+0

@Alon - 나는 그것을 심각하게 의심합니다. – karim79

5

내가이 작동하는지 아무 생각이 없다,하지만 ... :

${"[style*=width: 750px]") 

그러나 클래스를 사용하여 너비를 제어 한 다음 해당 클래스의 모든 인스턴스의 너비를 수정하거나 다른 클래스로 변경하는 것이 더 나을 수 있습니다.

반드시
$(".classname").removeClass("classname").addClass("otherclassname"); 
+0

@R. Bemrose - 나는 당신의 게시물을 보았을 때 그것이 효과가있을 것이라고 생각했지만, 행운이없는 몇 가지 시나리오에서 그것을 시도했습니다. Prototype에서 비슷한 것을 할 수 있다고 생각합니다. jQuery에서 할 수없는 것은 너무 나쁘다. – karim79

1

이 오래된 일이지만, 조나단 델 Strother의 대답 덕분에, 그것은 나를 조금 더이을 완성하는 방법에 대한 생각을 가지고 :

(function($){ 

    // Add commonly used regex to the jQuery object 
    var regex = { 
     digits: /^(-?\d+(?:\.\d+)?)([a-zA-Z]+)?$/ 
     ,expr: /^([\w-]+)\s*([:=<>])\s*([\w-\.]+(?:\([^\)]+\))?)$/ 
    }; 

    // Create a custom jQuery function that allows a bit more useful CSS extraction 
    $.fn.extend({ 
     cssExtract: function(cssAttr) { 

      var val = {prop:this.css(cssAttr)}; 

      if (typeof val.prop === "string") { 
       var match = regex.digits.exec(val.prop); 
       if (match) { 
        val.int = Number(match[1]); 
        val.metric = match[2] || "px" 
       } 
      } 

      return val; 

     } 
    }); 

    // Create the custom style selector 
    $.find.selectors[":"].style = function(el, pos, match) { 

     var search = regex.expr.exec(match[3]); 

     if (search) { 

      var style = search[1] 
       ,operator = search[2] 
       ,val = search[3] 
       ,target = $(el).cssExtract(style) 
       ,compare = (function(result){ 

       if (result) { 
        return { 
         int: Number(result[1]) 
         ,metric: result[2] || "px" 
        }; 
       } 

       return null; 

      })(regex.digits.exec(val)); 

      if (
       target.metric 
       && compare && compare.metric 
       && target.metric === compare.metric 
      ) { 

       if (operator === "=" || operator === ":") { 
        return target.int === compare.int; 
       } else if (operator === "<") { 
        return target.int < compare.int; 
       } else if (operator === ">") { 
        return target.int > compare.int; 
       } 

      } else if (target.prop && (operator === "=" || operator === ":")) { 
       return target.prop === val; 
      } 

     } 

     return false; 

    }; 

})(jQuery); 

사용자 정의 style 선택기로 다음과 같이 쉽게 쿼리 할 수 ​​있습니다.

$("div:style(height=57)") 

이 답변 시점에서 스택 오버플로 (이 페이지)의 최상위 div 요소를 반환해야합니다.이 같은

뭔가도 작동합니다

$("h3:style(color:rgb(106, 115, 124))") 

시도 브라우저에서 개발자 도구의 코드를 추가. Chrome에서 테스트 해 보았습니다. 다른 사람들에게도 테스트하지 않았습니다. 나는 또한 기존의 다른 라이브러리/플러그인을 연구하는 데 많은 노력을 기울이지 않았다.

관련 문제