javascript - 在元素高度旁边滚动图像

标签 javascript jquery html css

我正在尝试实现与其当前相邻的元素相关的 top 属性增加。元素只需要在元素旁边滚动,并在超过元素高度时停止。

我想要实现的目标:图像需要使用 jQuery 贴在元素的右边,并停在元素的末尾。

var objectSelect = $(".article");
var objectPosition = objectSelect.offset().top;

//if (scroll > objectPosition) {
//  objectSelect.find('article').addClass("fixable").find('figure').addClass("fixable");
//} else {
//  objectSelect.find('article').removeClass("fixable").find('figure').removeClass("fixable");
//}
body{
  
  height:1000px;
  
  }

.article {
  width: 100%;
  display: block;
}
.wrapper {
  position: relative;
}
figure {
  position: absolute;
  left: 0;
  top: 0;
  width: 50%;
  padding: 0;
  margin: 0;
  overflow: hidden;
}
.other-content {
  background-color: black;
  float: right;
  overflow: hidden;
  display: block;
  width: 50%;
  height: 800px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="article">
  <div class="wrapper">
    <figure>
      <img src="https://placeholdit.imgix.net/~text?txtsize=53&txt=566%C3%97780&w=566&h=500" />
    </figure>
    <div class="other-content">

    </div>
  </div>
</div>

最佳答案

您可以使 figure 元素固定,直到它的底部到达 .other-content 的底部,然后使用 bottom: 0 使其绝对定位,然后当您向上滚动超过 figure 元素的顶部时移除绝对定位。

var $figure = $('figure'),
  $other = $('.other-content'),
  other_bottom = $other.offset().top + $other.outerHeight();

$(window).on('scroll', function() {
  var scroll = $(window).scrollTop(),
    figure_top = $figure.offset().top,
    figure_bottom = $figure.offset().top + $figure.outerHeight();
  if (!$figure.hasClass('abs') && figure_bottom >= other_bottom) {
    $figure.addClass('abs');
  }
  if ($figure.hasClass('abs') && scroll < figure_top) {
    $figure.removeClass('abs');
  }
});
body {
  height: 500vh;
  margin: 0;
}

.article {
  width: 100%;
  display: block;
}

.wrapper {
  position: relative;
  overflow: auto;
}

figure {
  position: fixed;
  left: 0;
  top: 0;
  width: 50%;
  padding: 0;
  margin: 0;
  overflow: hidden;
}

.abs {
  position: absolute;
  bottom: 0;
  top: auto;
}

.other-content {
  background-color: black;
  float: right;
  overflow: hidden;
  display: block;
  width: 50%;
  height: 800px;
}

img {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="article">
  <div class="wrapper">
    <figure>
      <img src="https://placeholdit.imgix.net/~text?txtsize=53&txt=566%C3%97780&w=566&h=500" />
    </figure>
    <div class="other-content">
    </div>
  </div>
</div>

关于javascript - 在元素高度旁边滚动图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42213000/

相关文章:

javascript - 使用 nodemailer 发送邮件

javascript - 如何循环显示 Javascript 多维数组

javascript - 异步 keyup 事件/如何短路顺序 keyup 事件以提高速度

html - 样式文件上传 'Browse' 按钮

javascript - (state = {}) => state 是什么意思

javascript - jquery 从数组中删除最后 2 个零

javascript - 将数组插入循环内的对象

jquery - 容器高度设置为容器中最后一个子项的 css 顶部 + 几像素

css - 更改数据内容中的字体大小

javascript - 立即下载不断变化的背景图片