【问题标题】:Cheking if div is visible [duplicate]检查div是否可见[重复]
【发布时间】:2015-02-21 22:57:51
【问题描述】:

我正在使用 Popcorn.js,它会创建以下 HTML 代码:

<div id="row-1">
    <div style="display: none;">Hello</div>
</div>

但是当#row1 中的div 是display: inline 时,我现在尝试使用jQuery 将.myClass 添加/删除到.test

我试过.height().lenght().width()(但是这个不行,因为div的宽度总是1246px

任何帮助将不胜感激!


** 编辑 **

整个 HTML 代码:

<html>
  <head>
    <script src="http://popcornjs.org/code/dist/popcorn-complete.min.js"></script>

    <script src="js/jquery-1.11.2.min.js"></script>

        <style>
        .myClass{
          background: yellow !important;
        }
        </style>

    <script>
      // ensure the web page (DOM) has loaded
      document.addEventListener("DOMContentLoaded", function () {

           // Create a popcorn instance by calling the Youtube player plugin
         var example = Popcorn.youtube(
           '#video',
           'https://www.youtube.com/embed/w9l4v1s9148?controls=1' );

         example.footnote({
           start: 1.2,
           end: 1.7,
           text: "Hello",
           target: "row-1"
         });

         example.footnote({
           start: 1.7,
           end: 3.2,
           text: "boys and girls",
           target: "a2"
         });

         example.footnote({
           start: 3.2,
           end: 4.8,
           text: "my name is FatLip,",
           target: "a3"
         });

         example.footnote({
           start: 4.8,
           end: 7,
           text: "and this is my friend, Simon the Salmon.",
           target: "a4"
         });


      }, false);
    </script>
</head>

<body>
  <div id="video" style="width: 360px; height: 300px;" ></div>

  <div id="row-1"></div>
  <div id="a2"></div>
  <div id="a3"></div>
  <div id="a4"></div>

  <div class="test" style="width: 10px; height: 10px; background: black;"></div>
</body>
</html>

【问题讨论】:

  • 试试$(el).is(":visible")

标签: jquery css dom visibility


【解决方案1】:

jQuery 有选择器visible 所以你可以检查.is(':visible')

【讨论】:

    【解决方案2】:

    要查看子 div 是否可见,可以执行以下操作 -

    $('#row-1').children().is(':visible')

    !$('#row-1').children().is(':hidden')

    $('#row-1').children().css('display') == 'none'

    但要回答你的问题,你可以这样做 -

    如果你想寻找display: inline,你可以这样做-

    $('#row-1').children().filter('div[style*=display: inline]').addClass('myClass')

    如果您想查看它是否可见然后添加/删除类,您可以执行以下操作 -

    $('#row-1').children().filter(':hidden').addClass('myClass') // 或 removeClass

    【讨论】:

    • none 不是声明变量
    • 对不起.. 没注意到
    【解决方案3】:

    由于第一个 div 有一个 id,我们可以使用它来获取它的第一个子元素并检查该子元素的显示值是否等于 inline。

    // pure javascript
    
    if (document.getElementById('row-1').firstChild.style.display === 'inline') {
        // add/remove class
    }
    

    【讨论】:

    • 看起来这是正确的答案,但您可能需要稍微扩展一下以解释为什么这样可以解决问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 2012-09-14
    • 2011-07-18
    • 2012-12-07
    相关资源
    最近更新 更多