代码之家  ›  专栏  ›  技术社区  ›  Nrc

检测是否显示DIV-差异与空DIV?

  •  0
  • Nrc  · 技术社区  · 7 年前

    如何知道DIV是否不可见?我尝试了不同的方法,但在所有情况下,如果有一个带有CSS的DIV display: none 它认为它是“满的”。我可以检查“是否显示无或空”。但是有没有什么方法可以检测到所有的病例呢?

    	// Different ways to say that a div is empty:
    	//var empty = $("#a").html() == "";
    	//var empty = $("#a").text() == "";
    	//var empty = $('#a').text().length == 0
    	//var empty = $('#a').contents().length == 0;
    	//var empty = $('#a').is(':empty');
    	
    	// if there is a div display none, it's considered full:
    	if ( empty ) {
    		$("#check").text("a is empty");
    	}
    	else {
    		$("#check").text("a is full");
    	}
    	
    #a { display: none; }
    <div id='a'>
    	<div>something</div>
    </div>	
    
    <div id='check'></div>
    2 回复  |  直到 7 年前
        1
  •  2
  •   benvc    7 年前

    display: none .css()

    var display = $('#a').css('display');
    
    if (display === 'none') {
      // do something
    }
    

    const elems = $('.foo');
    
    elems.each(function() {
      let content = $(this).html().length;
      let display = $(this).css('display');
      if (content && display !== 'none') {
        console.log(this.id, 'displayed and not empty');
      } else {
        console.log(this.id, 'empty or not displayed');
      }
    });
    <div class="foo" id="bar" style="display: none;">
      <div>
        Something
      </div>
    </div>
    <div class="foo" id="baz"></div>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        2
  •  1
  •   empiric    7 年前

    div

    var elems = $('#a').contents();
    var empty = elems.length == 0;
    var containsVisibleElement = false;
    elems.each(function(i, v) { //loop though all contained elemetns
      containsVisibleElement = $(this).is(':visible'); //check if element is visible
      if (containsVisibleElement ) {
        return false; //break out of loop as one visible is enough for our check
      }
    });
    
    if (empty || !containsVisibleElement) {
      $("#check").text("a is empty");
    } else {
      $("#check").text("a is full");
    }
    #a div {
      display: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id='a'>
      <div>something</div>
    </div>
    
    <div id='check'></div>