Use the CSS style position:fixed horizontal scrolling method

  • 2020-03-30 01:46:48
  • OfStack

Using the CSS style "position:fixed" keeps the div block in a fixed position, even with the scrollbar. Position :fixed has been amazing for many developers, but when it comes to horizontal scrollbars, the effect is less acceptable. Sometimes we want the div block to be able to move left and right with the scroll bar when it appears, to achieve vertical fixed positioning and horizontal relative positioning. This article provides a solution, with jquery extension source code.

The implementation of this article is to use js to control the horizontal scrolling of the div block with the scroll bar. The principle is that when the window object has scroll event and resize event, the left or right value of the div block is updated, so that it changes in real time relative to the left or right position of the browser. The div block is required to modify the position:fixed style.

When the div block is fixed in the horizontal direction relative to the right side of the browser, when the window object has scroll or resize event, it will update its right style value, which should be:
 
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 of the browser, the left style value of the window object will be updated when a scroll or resize event occurs. The value should be:
 
var new_left = (original_left - $(window).scrollLeft()) + 'px' 

The original_left and original_right that occur in the code above 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 examples:
 
$('#leftsider').scrollFixed({fixed:'left'}); 
$('#rightsider').scrollFixed({fixed:'right'}); 

Related articles: