Using the CSS style "position:fixed" allows the div block to be fixed in a fixed position, and its position will not be changed 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, achieving vertical fixed positioning (fixed) and horizontal relative positioning (absolute). This article provides a solution, with jquery extension source code.
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 to update the left or right value of the div block to the left or right position of the browser. Change in real time. The position:fixed style modification when the div block is needed.
When the div block is fixed horizontally relative to the right side of the browser, then when a scroll or resize event occurs in the window object, its right-style value is updated, and its value should be:
The code copy is as follows:
var new_right = ($(window).scrollLeft() + $(window).width() - $(document).width() + original_right) + 'px'
When the div block is fixed in the horizontal direction relative to the left side of the browser, then when a scroll or resize event occurs in the window object, its left-style value is updated, and its value should be:
The code copy is as follows:
var new_left = (original_left - $(window).scrollLeft()) + 'px'
The original_left and original_right appear in the above code are the left and right values of the original div block. The complete jquery extension code is as follows:
The code copy 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);
Examples of usage:
The code copy is as follows:
$('#leftsider').scrollFixed({fixed:'left'});
$('#rightsider').scrollFixed({fixed:'right'});