使用CSS样式position:fixed水平滚动的方法_jquery

WBOY
Release: 2016-05-16 16:59:25
Original
1713 people have browsed it

使用CSS样式"position:fixed"可以使div块固定在一个固定位置,即使有滚动条也不会改变其位置。position:fixed给很多开发者带来了惊艳的效果,然而当出现水平滚动条时,效果就不那么容易接受了。有时候我们希望当出现水平滚动条时,div块可以随滚动条左右移动,实现垂直固定定位(fixed),水平相对定位(absolute)。本文提供一个解决方法,附jquery扩展源码。

本文的实现方式是使用js来控制div块随滚动条水平滚动,原理就是当window对象发生scroll事件和resize事件使,更新div块的left或right的值,使其相对浏览器左边或右边的位置实时改变。div块需要时position:fixed样式修饰。

当div块在水平方向上是相对浏览器右边固定的,那么当window对象发生scroll或resize事件时,就更新其right样式值,其值应该是:

复制代码代码如下:

var new_right = ($(window).scrollLeft() + $(window).width() - $(document).width() + original_right) + 'px'

当div块在水平方向上是相对浏览器左边固定的,那么当window对象发生scroll或resize事件时,就更新其left样式值,其值应该是:
复制代码代码如下:

var new_left = (original_left - $(window).scrollLeft()) + 'px'

上面代码中出现的original_left和original_right是最初div块的left和right值。完整的jquery扩展代码如下:
复制代码代码如下:

(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);

使用实例:
复制代码代码如下:

$('#leftsider').scrollFixed({fixed:'left'});
$('#rightsider').scrollFixed({fixed:'right'});
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!