您的位置:首页 > Web前端 > BootStrap

Bootstrap插件Affix问题解决

2017-02-17 00:00 316 查看
最近使用bootstrap affix插件,结果发现有几个小bug:

1. 当浏览器大小发生变化时, affix侧边导航栏的位置和高度不能很好的适应;

2. 当浏览器的大小发生改变时,affix侧边栏的宽度不能自适应,一般解决方法时固定宽度;

3. 当浏览器滚动条拉到底部时,affix侧边栏会和底部的footer发生干涉;

针对以上问题进行解决:采用jquery 的reszie事件和scroll事件进行响应编程,

里面的技巧是:先计算事件后后affix的位置和宽度,再通过.affix('checkPosition')更新affix位置,

由于resize和scroll事件的响应事件太快,浏览器实际上触发了多次,因此需要加上延迟处理。

保证事件发生后才进行计算更新affix位置。具体代码如下:

var timer=0;

//resize事件响应

$(window).resize(function(){

if(timer){

clearTimeout(timer);

timer=0;

}

timer=setTimeout(function(){

var $affixElement = $('ul[data-spy="affix"]');

$affixElement.width($affixElement.parent().width());

$('#nav').affix({

offset: {

top: $('#nav').offset().top,

bottom: ($('#footer').outerHeight(true)) + 40

}

});

$('#nav').affix('checkPosition');

/*alert("resize event");*/

},10);

$('#nav').affix('checkPosition');

});

//scroll事件响应

$(window).scroll(function(){

if(timer){

clearTimeout(timer);

timer=0;

}

timer=setTimeout(function(){

var $affixElement = $('ul[data-spy="affix"]');

$affixElement.width($affixElement.parent().width());

$('#nav').affix({

offset: {

top: $('#nav').offset().top,

bottom: ($('#footer').outerHeight(true)) + 40

}

});

$('#nav').affix('checkPosition');

/*alert("resize event");*/

},10);

$('#nav').affix('checkPosition');

});

如果觉得我的文章能帮你节省时间,就打个赏呗:)

版权所有,转载请注明出处!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐