当div位置固定时,JQuery Offset问题

时间:2017-11-05 05:47:04

标签: javascript jquery html css

我的网站有一个页面布局和样式,如JsFiddle

中所述

现在,当我点击按钮时使用JQuery,内容正在正确显示,如下所示:

enter image description here

但是当我第一次滚动页面然后单击按钮时,内容显示不正确,如下所示:

enter image description here

你能指导我处理这种情况吗?

我在下面使用了jQuery。但似乎offsetposition无效

$('#btn').click(function(){
    var t = $(this).offset();
  console.log(t);
  $('.control-container').css('top', t.top + 20 + 'px');
  $('.control-container').css('display', 'block');
});

$(document).on('scroll', function(){
$('.control-container').css('display', 'none');
});

3 个答案:

答案 0 :(得分:2)

此处无需特别提及position属性。

同时删除结束a代码并将其替换为</button>

目前容器占据全宽,但也可以设置

&#13;
&#13;
$('#btn').click(function() {
  var t = $(this).offset();
  console.log(t);
  $('.control-container').css('top', t.top + 30 + 'px');
  $('.control-container').css('display', 'block');
});

$(document).on('scroll', function() {
  $('.control-container').css('display', 'none');
});
&#13;
.header {
  background-color: maroon;
  color: #fafafa;
  height: 60px;
  position: fixed;
  width: 100%;
  text-align: center;
  line-height: 19px;
  font-size: 25px;
  z-index: 2;
  padding: 0px;
  margin: 0px;
  top: 0;
}

.content {
  background-color: #fff;
  border: 1px solid #999;
  padding: 5px;
  height: 100%;
  width: 100%;
  position: absolute;
  z-index: 1;
  top: 60px;
}

.control-container {
  width: auto;
  background-color: red;
  #position: fixed;
  color: #fff;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="header">
    Header
  </div>
  <div style="clear:both">

  </div>
  <div class="content">
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <button id="btn">Click Me</button>
    <div class="control-container" style="display:none;">
      Keep me exactly underneath 'Click Me' when Page is scrolled.
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您无需使用offset来实现这一目标......如果您需要将CSSposition:fixed保持一致,则需要在javascript中进行切换到static

您正在寻找的东西只是display:table ...

$('#btn').click(function(){
  $('.control-container').css({'display': 'table','position': 'static'});
});

$(document).on('scroll', function(){
   $('.control-container').css({'display': 'none','position': 'fixed'});
});

Check out this JSFiddle

但如果您确实需要基于position:fixed位置button的解决方案,那么您应该尝试这种方式:

$('#btn').click(function(){
    var button_fixed_position = $('#btn').get(0).getBoundingClientRect();
  $('.control-container').css({'display': 'block','left' : button_fixed_position.left, 'top' : button_fixed_position.bottom});
});

$(document).on('scroll', function(){
   $('.control-container').css({'display': 'none'});
});

Check out second JSFiddle

答案 2 :(得分:1)

CSS位置fixed属性定位一个引用视图&body / body维度的元素。

如果您有权修改CSS,那么只需从position: fixed;移除.control-container媒体资源。

如果您无法访问,请使用脚本将position: static !important属性添加到.control-container

$('.control-container').css('cssText', 'position: static !important');

修改后的JSFiddle

相关问题