繁体   English   中英

为什么我的函数不能在.resize()上运行?

[英]Why doesnt my function run on .resize()?

我已经创建了一个使用jQuery将我的<div>居中的函数,该函数在页面加载时有效,但在页面调整大小时不起作用。

我究竟做错了什么?

JS:

<script>
    $( document ).ready(function() {
        function reCenter() {
            $('.content').css({
                position:'absolute',
                left: ($(window).width() 
                    - $('.content').outerWidth())/2,
                top: ($(window).height() 
                    - $('.content').outerHeight())/2
            });             
        }
        $(window).resize(reCenter());
        // To initially run the function:
        reCenter();
    });
</script>

HTML:

<div class="content">
    <h1>Header</h1>
    <span class="hyphen">-</span>
    <h2>Subtext</h2>
</div>

CSS:

* {
            padding: 0;
            margin: 0;
        }
        html { 
            background: darkgrey;
        }
        body {
            color: #fff;
            text-align: center;
            /*padding-top: 300px;*/
        }
        h1 {
            font-family: 'Arimo', sans-serif;
            text-transform: uppercase;
            font-weight: bold;
            font-size: 40px;
        }
        span.hyphen {
            color: #0CFFFC;
            font-size: 3em;
        }
h2 {
            font-family: 'Montserrat', sans-serif;
            font-weight: 100;


        }

UPDATE
在使函数在页面加载时启动后,它在页面加载和窗口调整大小之间有一些不一致的行为http://jsfiddle.net/7zqkd4w8/

它应该是$(window).resize(reCenter); 因为您要向它发送一个函数,而不是调用该函数的结果。

您正在尝试查找'.content'div的宽度。 除非它是浮动的或绝对的,否则您将无法获得适当的div宽度。 您正在reCenter()中为.content提供绝对类; 因此,如果您两次触发调整大小功能(第一次),它将起作用。

$(window).on('resize',function(){
   reCenter()
}).resize().resize();

但是建议的方法是将浮点数添加到内容中,您现有的代码应该可以使用。

.content{
    float:left;
}

您应该这样做:

$(window).on('resize',function(){
   reCenter()
}).resize();//triggers on first page load

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM