使用jquery加载动画以在特定div中显示

时间:2016-08-19 06:07:53

标签: javascript jquery html css ajax

每当ajax调用发生时,我都会使用jQuery显示加载图标,如下所示:

$body = $("body");
$(document).on({
  ajaxStart: function() { $body.addClass("loading");    },
  ajaxStop: function() { $body.removeClass("loading"); }    
});
.modal {
  display:    none;
  position:   fixed;
  z-index:    1000;
  top:        0;
  left:       0;
  height:     100%;
  width:      100%;
  background: rgba( 255, 255, 255, .8 ) 
    url('http://i.stack.imgur.com/FhHRx.gif') 
    50% 50% 
    no-repeat;
}
body.loading {
  overflow: hidden;   
}
body.loading .modal {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal"><!-- Place at bottom of page --></div>

无论何时发生ajax都会正常加载,但很明显,加载图标会显示在隐藏后面UI的正文中。而不是我想要仅在特定div内显示加载。在附加的html文件中,我想只在

中进行加载显示
"div id= box1"

Link to HTML File

2 个答案:

答案 0 :(得分:0)

vijayP的评论是正确的方向。

由于您只将加载类限制为body元素,因此必须修改CSS。

.loading {
   overflow: hidden;   
}
.loading .modal {
   display: block;
}

然后在JavaScript中:

$(document).on({
  ajaxStart: function() { $("#box1").addClass("loading");    },
  ajaxStop:  function() { $("#box1").removeClass("loading"); }    
});

答案 1 :(得分:0)

我已经编辑了一下你的代码,我希望现在能让你继续。

$body = $("body");
$(document).on({
  ajaxStart: function() { $body.addClass("loading");    },
  ajaxStop: function() { $body.removeClass("loading"); }    
});
.modal {
  display:    none;
  position:   fixed;
  z-index:    1000;
  top:        0;
  left:       0;
  height:     100%;
  width:      100%;
  /*background: rgba( 255, 255, 255, .8 ) 
    url('http://i.stack.imgur.com/FhHRx.gif') 
    50% 50% 
    no-repeat;*/
}
body.loading {
  overflow: hidden;   
}
body.loading .modal {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal">
<img src="http://i.stack.imgur.com/FhHRx.gif" />
<!-- Place at bottom of page --></div>

相关问题