Select Element By CSS style (all with given style)

前端 未结 4 1206
无人共我
无人共我 2020-12-09 13:44

Is there a way to select all elements that have a given style using JavaScript?

Eg, I want all absolutely positioned elements on a page.


I would assume

相关标签:
4条回答
  • 2020-12-09 14:00

    There is no selector for CSS attributes, so you're pretty much stuck to looping through each element and checking it's position. Here's a jQuery method:

    $("*").each(function() {
        var pos = $(this).css('position');
        if(pos == "absolute") {
            // do something
        }
        else if (pos == "relative") {
            // do something else
        }
    });
    

    You can use Case statements instead of if/else as well.

    Other than this solution, there is no selector per se that can search by CSS attributes (unless they were inline, maybe).

    0 讨论(0)
  • 2020-12-09 14:11

    For Mootools:

    var styleEls = $$('*').filter(function(item) {
        return item.getStyle('position') == 'absolute';
    });
    
    0 讨论(0)
  • 2020-12-09 14:13

    You can keep Mootools, or whatever you use... :)

    function getStyle(el, prop) {
      var view = document.defaultView;
      if (view && view.getComputedStyle) {
        return view.getComputedStyle(el, null)[prop];
      }
      return el.currentStyle[prop];
    }
    
    ​function getElementByStyle(style, value, tag)​ {
      var all = document.getElementsByTagName(tag || "*");
      var len = all.length;
      var result = [];
      for ( var i = 0; i < len; i++ ) {
        if ( getStyle(all[i], style) === value )
          result.push(all[i]);
      }
      return result;
    }
    
    0 讨论(0)
  • 2020-12-09 14:15

    In jQuery you could use

    $('*').filter( function(){
      return ($(this).css('position') == 'absolute');
    } );
    

    [update]

    Or even create a new selector.
    got me interested and so here is one (its my 1st, so its not built for efficiency) to find elements by css property..

    $.expr[':'].css = function(obj, index, meta, stack){
      var params = meta[3].split(',');
    
      return ($(obj).css(params[0]) == params[1]);
    };
    

    usage: $('optionalSelector:css(property,value)')
    will return all elements (of optionalSelector) whose property = value

    example: var visibleDivs = $('div:css(visibility,visible)');
    will return all divs whose visibility is set to visible (works for the default visibility as well..)

    0 讨论(0)
提交回复
热议问题