JQuery .center 不是一个函数



我正在研究JQuery。我收到此错误。我试图找出根本原因,但我找不到它。如果有人能帮助我,那就太好了。

JS 错误:

Uncaught TypeError: $(...).center is not a function
at HTMLDivElement.<anonymous> (myjs:879)
at HTMLDivElement.opt.complete (jquery-1.8.3.js:9154)
at fire (jquery-1.8.3.js:974)
at Object.add [as done] (jquery-1.8.3.js:1020)
at Animation (jquery-1.8.3.js:8719)
at HTMLDivElement.doAnimation (jquery-1.8.3.js:9034)
at Function.dequeue (jquery-1.8.3.js:1895)
at HTMLDivElement.<anonymous> (jquery-1.8.3.js:1938)
at Function.each (jquery-1.8.3.js:611)
at init.each (jquery-1.8.3.js:241)

我的脚本:

function centerdiv() {
    $('#id').show(0, function () {
         $('#id1').css('z-index','5');
        $('body').css('overflow', 'hidden');
        $('.class').center();
    });
}

所有 JQuery 函数都在工作,我不确定为什么它说 .center 不是一个函数。

您的错误告诉您没有$.center()。 但是,你可以做一个!

这是托尼·

jQuery.fn.center = function(parent) {
    if (parent) {
        parent = this.parent();
    } else {
        parent = window;
    }
    this.css({
        "position": "absolute",
        "top": ((($(parent).height() - this.outerHeight()) / 2) + $(parent).scrollTop() + "px"),
        "left": ((($(parent).width() - this.outerWidth()) / 2) + $(parent).scrollLeft() + "px")
    });
return this;
}
$("div.target:nth-child(1)").center(true); // Center relitive to parent
$("div.target:nth-child(2)").center(false); // Center relitive to window
div.container{
    width:200px;
    height:200px;
    border:1px solid #555;
    position:relative;
    top:10px;
    left:10px;
}
div.target{
    width:60px;
    height:60px;
    color:white;
    background:rgba(30,30,30,.7);
    border-radius: 10px;
    text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <div class="target">1<br>parent</div>
    <div class="target">2<br>window</div>
</div>

该错误意味着$.center()不是您可以使用的jQuery方法。与其尝试调用不存在的方法,不如更改 CSS 以居中某些内容。例如:

使用 jQuery 垂直和水平居中div

您可以创建自己的center方法,但不能只调用$.center()因为它不存在。

最新更新