看了不少网站为了提高用户体验,都采用了重要的菜单项可根据需要固定在屏幕某个位置的做法。于是我也来实现一把。
主要有两个要点,一个是要捕获页面滚动条的位置,一个是要将元素固定。后者用样式一句话搞定如:
固定样式的CSS写法:
.fixed {
position: fixed;
top: 1px;
}
下面是脚本的实现,分为两种形式:
(1)html页面中直接使用
...
(2)写成jQuery插件的形式
(function($) {
$.fn.fixme = function(options) {
var defaults = {
scroll_top_threshold : 0, //滚动条位置变更点px-滚动条到该点后,相应元素被固定或被解除固定
fixed_css : 'fixed', //引入的固定的样式名
fix_element : this, //被固定的页面元素
fixed: false, //目前该元素是否被固定
};
// Extend our default options with those provided.
var opts = $.extend(defaults, options);
// Our plugin implementation code goes here.
//alert($(opts.fix_element).html());
$(window).scroll(function() {
var top = 0;
if (document.documentElement && document.documentElement.scrollTop) {
top = document.documentElement.scrollTop;
left = document.documentElement.scrollLeft;
width = document.documentElement.scrollWidth;
height = document.documentElement.scrollHeight;
} else if (document.body) {
top = document.body.scrollTop;
left = document.body.scrollLeft;
width = document.body.scrollWidth;
height = document.body.scrollHeight;
}
if(top>opts.scroll_top_threshold){
if(!opts.fixed){
$(opts.fix_element).addClass(opts.fixed_css);
opts.fixed = true;
}
}else{
$(opts.fix_element).removeClass(opts.fixed_css);
opts.fixed = false;
}
});
};
})(window.jQuery);
--jQuery插件在页面应用--
$(document).ready(function(){
$(".inline").colorbox({inline:true, width:"510", height:"230", scrolling:false});
$(".well").fixme({scroll_top_threshold : 110}); //<==here 把class=well的页面元素当屏幕垂直滚动条的位置>110时,该元素固定
});
此文章由 http://www.ositren.com 收集整理 ,地址为:
http://www.ositren.com/htmls/68346.html