TypeError:无法读取null的属性'css'

时间:2015-01-11 14:03:08

标签: javascript jquery html css twitter-bootstrap

我试图通过引用其类名来设置我的div元素的最小高度,但它返回错误: TypeError:无法读取属性' css'为null

HTML元素

<div class="container contentContainer" id="topContainer">
        <div class="row">
            <div class="col-md-6 col-md-offset-3" id="topRow">
                <p class="bold">Please scroll down for more information </p>
            </div>
        </div>
    </div>

的Javascript

<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>

<script>
    $(function () {
        var x = document.getElementsByClassName("contentContainer");
        alert(x);
        if(x != null)
        {
            $(".contentContainer").css('min-height',$(window).height());
        }
    });
</script>

有关为什么会出现此错误的任何建议?请告诉我。

当我包含外部javascript文件时会出现问题:

<!-- <script type="text/javascript" src="js/monthly.js"></script> -->

6 个答案:

答案 0 :(得分:10)

您同时加载了jQuery和Bootstrap,它们都破坏了$符号;要仅使用jQuery,您将使用规范名称:

jQuery(".contentContainer")
    .css('min-height', jQuery(window).height());

或者,使用包装器:

jQuery(function($) {
    $(".contentContainer").css('min-height',$(window).height());
});

答案 1 :(得分:0)

这是jQuery语法。

$(window).height();

您需要包含jQuery或使用本机JavaScript版本:

window.innerHeight;

要使用jQuery,您需要包含jQuery library

答案 2 :(得分:0)

您在JSFiddle上收到错误,因为您没有包含jQuery。

Updated Fiddle

在左侧导航栏上,有一个部分显示“框架和扩展程序”。您需要选择

jQuery (edge)

或该下拉列表中的任何jQuery版本。

JSFiddle side-bar

因为你没有包含jQuery,$构造函数不存在,所以错误

TypeError: cannot read property 'css' of null.

因为您尝试访问不存在的(null)对象的属性而被抛出。

答案 3 :(得分:0)

var x = document.getElementsByClassName("contentContainer");

返回具有该类的元素数组。像在普通数组中一样访问所需元素。

x[0]     //The first element, if there is any.

答案 4 :(得分:0)

如果您在浏览器控制台上键入$ [ENTER],您会得到类似

的内容
function (a,b){return new e.fn.init(a,b,h)

如果选择器$('。contentContainer')返回null而不是包含函数css的对象,则可能$不引用jQuery,或者在包含jquery.js和您尝试运行的代码之间进行了更改。

答案 5 :(得分:0)

如果在使用bootstrap-dialog时发生错误,请注释掉bootstrap-dialog.js文件中的以下代码行:

$ backdrop.css('z-index',zIndexBackdrop +(dialogCount-1)* 20);

这将停止“ TypeError:无法读取null的属性'css'”错误。

如果使用bootstrap-dialog时未发生错误,请打开相关的js文件,然后注释掉其中的所有css文件引用,然后重新运行网页。它应该成功运行。然后一一取消注释代码行,然后重新测试该页面,直到再次中断。最终,这将导致您进入到反派代码行,然后可以将其注释掉,避免继续出现此错误。