Using the CSS style "position:fixed" can fix the div block in a fixed position, and its position will not change even if there is a scroll bar. position:fixed has brought amazing effects to many developers, but when horizontal scroll bars appear, the effect is not so easy to accept. Sometimes we hope that when a horizontal scroll bar appears, the div block can move left and right with the scroll bar to achieve vertical fixed positioning (fixed) and horizontal relative positioning (absolute). This article provides a solution, with jquery extension source code attached.
The implementation method of this article is to use js to control the div block to scroll horizontally with the scroll bar. The principle is that when the scroll event and resize event occur in the window object, the left or right value of the div block is updated so that it can be viewed relatively The position of the left or right side of the monitor changes in real time. The div block is modified with position:fixed style when needed.
When the div block is fixed relative to the right side of the browser in the horizontal direction, then when the scroll or resize event occurs on the window object, its right style value is updated, and its value should be:
var new_right = ($(window).scrollLeft() $(window).width () - $(document).width() original_right) 'px'
When the div block is fixed horizontally relative to the left side of the browser, then when the scroll or resize event occurs on the window object , update its left style value, its value should be:
var new_left = (original_left - $(window).scrollLeft()) 'px'
The original_left and original_right that appear in the above code are the left and right values of the original div block. The complete jquery extension code is as follows:
(function($) {
$.ScrollFixed = function(el, options){
var base = this;
base.$el = $(el);
base.el = el;
var target = base.$el;
var original_left = parseInt(target.css('left'));
var original_right = parseInt(target.css('right'));
var _fix_position = function(){
if(base.options.fixed == 'right'){
target.css('right', ($(window).scrollLeft() $(window).width() - $(document).width() original_right) 'px');
} else if(base.options.fixed == 'left'){
target.css('left', (original_left - $ (window).scrollLeft()) 'px');
}
};
var windowResize = function(){
_fix_position();
};
var windowScroll = function(){
_fix_position();
};
base.init = function(){
base.options = $.extend({}, $.ScrollFixed.defaultOptions, options);
$(window).resize(windowResize);
$(window).scroll(windowScroll);
_fix_position();
console.log(base .options.fixed);
};
base.init();
};
$.ScrollFixed.defaultOptions = {
fixed:'left'
};
$.fn.scrollFixed = function(options){
return this.each(function(){
(new $.ScrollFixed(this, options));
});
};
})(jQuery);
Usage example:
$('#leftsider').scrollFixed({fixed:'left'});
$('#rightsider').scrollFixed( {fixed:'right'});