jQuery outerHeight()即使使用jQuery(window).load()也返回0

时间:2013-11-07 09:24:21

标签: javascript jquery ajax outerheight

在我用ajax加载内容后,我想获得已加载元素的outerHeight。

Ajaxload文件:

$('#workshop').submit(function(event){



        $.ajax({
        url: URL,
        type: 'POST',
        data: $('#workshop').serialize(),
        success: function(data){

            var string = '<div class="section" id="result"></div>';

            if(prevent == true){
                 $('#container #result').html($("#main .inside>.mod_article", data));

                 $.getScript( scriptURL, function() {
                        });
            }else{
                $('#container').append(string);
                $('#container #result').html($("#main .inside>.mod_article", data));


                    $.getScript( scriptURL, function() {
                        });


                prevent = true;

            }

    });
        event.preventDefault();
});

加载的脚本如下所示:

var height;
var top ;

function scroll_down(){

jQuery(window).load(function(){
    $('.result_control .up').css({'display' : 'block'});

    top = $('.item_wrapper>.inner').css('top');
     height =  $('.item_wrapper>.inner>.item').outerHeight(true);

});

console.log(top);
console.log(height);

}


function scroll_up(){
console.log('up');
}

$('.item_wrapper').mousewheel(function(event, delta, deltaX, deltaY){
if(delta > 0){
    scroll_up();
}else if(delta < 0){
    scroll_down();
}
 });

加载元素的HTML:

<div class="item_wrapper">
  <div class="inner">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
  </div>
</div>

这些元素的css代码:

.section#result .workshopfilter .filterresult .item_wrapper {
overflow: hidden;
width: 100%;
height: 65%;
position: relative;
clear: both !important;
}
.section#result .workshopfilter .filterresult .inner {
position: absolute;
top: 0px;
width: 100%;
clear: both !important;
 }
.section#result .workshopfilter .filterresult div.item {
float: left;
margin-right: 1%;
margin-left: 1%;
margin-bottom: 2%; 
width: 27%;
background-color: #ffff00;
color: #333;
height: 250px;
padding: 2%;
position: relative;
display: block;
font-family:'AmericanTypwrterITCW01- 731031';
}

.css()返回对象

.outerHeight返回0

元素可见并显示:块。 我不知道如何解决它以获得正确的属性。

1 个答案:

答案 0 :(得分:0)

因为ajax是异步的。你需要在load ()的回调函数中指定变量,在你的情况下是在

之外
 jQuery(window).load(function(){
    $('.result_control .up').css({'display' : 'block'});
    top = $('.item_wrapper>.inner').css('top');
    height =  $('.item_wrapper>.inner>.item').outerHeight;

    console.log(top);  //here
    console.log(height); //here

});

因为你在加载回调函数之外有你的console.log ..在load完成之前调用console.log所以什么都不给你