【问题标题】:jQuery css fixed left but absolute topjQuery css 固定左侧但绝对顶部
【发布时间】:2013-05-04 05:41:42
【问题描述】:

我一直很难将一个元素固定到页面左侧,但也能够上下滚动。

我已经尝试过将左侧位置更改为 $(window).scrollLeft() 的方法,但这会产生一个非常不稳定的动画。

我正在寻找的是这个小提琴的反面,但我不能让它工作:

http://jsfiddle.net/F7Bme/

var leftInit = $(".scroll_fixed").offset().left;
var top = $('.scroll_fixed').offset().top - parseFloat($('.scroll_fixed').css('margin-       top').replace(/auto/, 0));

$(window).scroll(function(event) {
   var x = 0 - $(this).scrollLeft();
   var y = $(this).scrollTop();

// whether that's below the form
if (y >= top) {
    // if so, ad the fixed class
    $('.scroll_fixed').addClass('fixed');
} else {
    // otherwise remove it
    $('.scroll_fixed').removeClass('fixed');
}

$(".scroll_fixed").offset({
    left: x + leftInit
   });
});

请注意,这个 div 是固定在顶部而不是左侧。我正在寻找相反的,固定的左侧而不是顶部。有什么想法吗?

我尝试编辑此小提琴,但无法正常工作。

【问题讨论】:

  • 如果窗口水平滚动一半然后垂直滚动而不返回水平滚动到0,会发生什么?

标签: jquery css jquery-ui css-position


【解决方案1】:

这锅:

var leftInit = $(".scroll_fixed").offset().left;
var top = $('.scroll_fixed').offset().top - parseFloat($('.scroll_fixed').css('margin-top').replace(/auto/, 0));

$(window).scroll(function(event) {
  var x = $(this).scrollLeft();
  var y = $(this).scrollTop();

  // whether that's below the form
  if (x >= leftInit) {
      // if so, ad the fixed class
      $('.scroll_fixed').addClass('fixed');
  } else {
      // otherwise remove it
      $('.scroll_fixed').removeClass('fixed');
  }

  $(".scroll_fixed").offset({
      left: x + leftInit
  });
});

编辑也改

.scroll_fixed.fixed {
  position:absolute;

【讨论】:

  • 它对我不起作用...它固定在左侧,但也固定在顶部,我只希望它固定在左侧而不是顶部。
【解决方案2】:

也许这就是你想要的http://jsfiddle.net/F7Bme/958/

.scroll_fixed {
    position: relative;
    float: left;
    left: 0;
}
.scroll_fixed div {
    float: left;
    position: relative
} 

忘记了 JS

【讨论】:

  • 这可能是一个简化的例子。对于 OP 认为与问题无关但很好的答案的部分功能,JS 可能是必需的。
猜你喜欢
  • 2015-02-04
  • 1970-01-01
  • 1970-01-01
  • 2011-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
相关资源
最近更新 更多