-1

嗨,我有一个隐藏的 div,在其中我有可见的跨度。如果 span 没有 display none 属性,我想提醒一些文本。

<head>
    <script type="text/javascript">
        $(function() {
            if($('span').is(':visible')){
                alert(0)
            }
        })
    </script>
</head>
<body>
    <div class="fa" style="display:none">
        <span>sdf</span>
    </div>
</body>
4

4 回答 4

3

根据jQuery API

如果元素占用了文档中的空间,则元素被认为是可见的。可见元素的宽度或高度大于零。

Your <span> is a child of a <div> that's hidden with display: none - that means neither the <div>, nor the <span> consume any space in the document.

Which means that your <span> is hidden and your script has no errors - it does exactly what it suppose to do.

于 2013-01-14T18:42:55.393 回答
1

你不导入 jQuery。

head在你的元素中添加这个:

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>

请注意,HTML 文件还必须具有 HTML 开始和结束元素,最好是 doctype。以下文件有效:

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(function(){
      if($('span').is(':visible')){
       alert(0)
    }})
    </script>
</head>
<body>
<div class="fa" style="display:none">
<span>sdf</span>
</div>
</body>
</html>

它什么也不做,因为您的跨度位于未显示的 div 中。

现在,如果您想准确地知道您的元素是否没有直接设置样式 display=none ,请像这样测试它:

if ($('span').get(0).style.display!='none') {

示范

于 2013-01-14T18:39:27.820 回答
1

The reason your alert doesn't fire is that your span isn't visible. The fact that it is contained within an element that has display: none means that it will not be shown. If you specifically want to check if it is display: none itself, use css.

        if($('span').css('display') != "none"){
            alert(0)
        }
于 2013-01-14T18:43:46.010 回答
0

Your problem is that the div containing the span element has display:none as property, try this Fiddle, you just put display:hidden instead of none and the JS works.

<div class="fa" style="display:hidden"><span>sdf</span></div>
于 2013-01-14T18:45:05.530 回答