Bootstrap为了让全部的页面(这里指内容溢出和不溢出)显示效果同样,采起的方法以下:css
当Modal显示时,设置body -- overflow:hidden;margin-right:15px;(设置15px是由于浏览器的滚动条占位是15px);(经过在modal显示时给body添加.modal-open类实现)bootstrap
设置modal -- overflow:auto;overflow-y:scroll;浏览器
这样设置的效果是:ide
(1)当页面内容超出(即页面自己存在滚动条),则moda弹出后,原body滚动禁止,body的margin-right和modal的滚动条位置重叠,此时页面是不会出现抖动现象的;函数
(2)当页面内容未超出(即页面自己不存在滚动条),则modal弹出后,因为body设置了margin-right,会使得页面向左偏移,当modal关闭后,body的margin-right为0,页面向右偏移,就出现页面抖动。this
根据上面的描述,解决页面抖动的思路是:spa
根据scrollHeight和clientHeight,分别在modal加载前和关闭时调整body的overflow、margin-right和.modal的overflow属性,以覆盖bootstrap.css中的样式prototype
函数以下:code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
//解决Modal弹出时页面左右移动问题
Modal.prototype.adjustBody_beforeShow = function(){
var
body_scrollHeight = $(
'body'
)[0].scrollHeight;
var
docHeight = document.documentElement.clientHeight;
if
(body_scrollHeight > docHeight){
$(
'body'
).css({
'overflow'
:
'hidden'
,
'margin-right'
:
'15px'
});
$(
'.modal'
).css({
'overflow-y'
:
'scroll'
})
}
else
{
$(
'body'
).css({
'overflow'
:
'auto'
,
'margin-right'
:
'0'
});
$(
'.modal'
).css({
'overflow-y'
:
'auto'
})
}
}
Modal.prototype.adjustBody_afterShow = function(){
var
body_scrollHeight = $(
'body'
)[0].scrollHeight;
var
docHeight = document.documentElement.clientHeight;
if
(body_scrollHeight > docHeight){
$(
'body'
).css({
'overflow'
:
'auto'
,
'margin-right'
:
'0'
});
}
else
{
$(
'body'
).css({
'overflow'
:
'auto'
,
'margin-right'
:
'0'
});
}
}
|
函数使用方法:orm
1
2
3
4
5
6
7
8
9
|
Modal.prototype.show = function (_relatedTarget) {
this
.adjustBody_beforeShow();
//...other code
}
Modal.prototype.hide = function (e) {
this
.adjustBody_afterShow();
//...other code
}
|