在使用layui的layer插件打开弹出层的时候,会出现弹出层的Iframe高度设置为默认的150px,这样会导致出现滚动条或者内容显示不全的现象。下面介绍几种优化方法:
1. 使用auto自适应高度和宽度
在弹窗的时候,将area设置为auto,让插件自适应高度和宽度。
```layui.layer.open({
type: 2,
area: ['auto', 'auto'],
content: 'www.ybb.press',
shade: 0.5,
title: '页面'
});
```
2. 使用success回调函数重新计算高度
在弹窗成功之后,使用success回调函数对iframe内容进行重新计算高度。
```layui.layer.open({
type: 2,
area: '300px',
shade: 0.5,
content: 'www.ybb.press',
success: function(layero, index) {
var iframe = layui.$(layero).find('iframe');
iframe.css('height', iframe[0].contentDocument.body.offsetHeight);
$(layero).css('top', (window.innerHeight - iframe[0].offsetHeight) / 2);
}
});
```
3. 使用iframeAuto方法自适应高度
在弹窗成功之后,使用iframeAuto方法对iframe进行重新高度定义。
```layui.layer.open({
type: 2,
area: '300px',
shade: 0.5,
content: 'www.ybb.press',
success: function(layero, index) {
layer.iframeAuto(index);
}
});
```
4. 使用resize事件重新计算高度
在弹窗成功之后,绑定resize事件,对iframe内容进行重新计算高度。
```layui.layer.open({
type: 2,
area: '300px',
shade: 0.5,
content: 'www.ybb.press',
success: function(layero, index) {
var iframe = layui.$(layero).find('iframe');
iframe.on('load', function() {
iframe.css('height', iframe[0].contentDocument.body.offsetHeight);
});
layui.$(window).on('resize', function() {
iframe.css('height', iframe[0].contentDocument.body.offsetHeight);
});
}
});
```
总结:
以上四种方法都可以实现弹出层高度自适应的效果,但是第一种方法会有局限性,第二种方法处理速度快,但是会有高度变化的视觉问题,第三种方法对于链接的iframe层的高度适应需要测试,第四种方法需要绑定resize事件,对性能有一定影响。根据实际情况选择合适的方法进行优化。
发表评论 取消回复