我在JS和前端方面是一个完全的初学者.我在一个网站上工作,我在这个div中有一张ID为main-image的图像.

当用户向下滚动图像时,我希望它慢慢向左滚动,然后删除图像.

var x = 0;
var screenWidth = window.innerWidth;

window.onscroll = function() {
  var box = document.getElementById("main-image");

  setInterval(function() {
    if (x <= screenWidth) {
      x++;
      box.style.left = x + "px";
    } else {
      box.style.display = "none";
    }
  }, 10);
}
.site-header {
  background-image: url("https://images.pexels.com/photos/2159065/pexels-photo-2159065.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=627&w=1200");
  height: 100vh;
  background-repeat: no-repeat;
  background-size: cover;
  justify-content: center;
  position: relative;
}

#main-image {
  position: marker;
  left: 0;
  transition: ease-out;
}
<div class="container-fluid site-header" id="main-image">
  <div class="image-on-text-container bg-secondary">
    <span class="site-brand"></span>
  </div>
</div>

我为这个写了这个 playbook ,但进展很糟糕.我希望它移动得慢一些,也许会有一些效果,但我不知道怎么做.

推荐答案

取而代之地计算y增量,并在计时值即:0.Ns上制作动画过渡,并在该增量值乘以y上平移x坐标以获得百分比值.不要忘记将overflow: hidden;添加到父元素中

const elBox = document.querySelector(".image-on-text-container");

const moveImage = () => {
  const rect = elBox.getBoundingClientRect();
  const yDelta = -rect.top / rect.height;
  const x = Math.max(0, yDelta); // prevent negative value (move only to left)
  elBox.style.translate = `${x * 100}% 0`;
};

addEventListener("scroll", moveImage); // Do on scroll
moveImage(); // and on init
* { margin: 0; box-sizing: border-box; }

.site-header {
  overflow: hidden; /* Remove scrollbars */
}

.image-on-text-container {
  position: relative;
  height: 100vh;
  background-image: url("https://images.pexels.com/photos/2159065/pexels-photo-2159065.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=627&w=1200");
  background-repeat: no-repeat;
  background-size: cover;
  transition: 0.2s ease-out;
}
<div class="container-fluid site-header" id="main-image">
  <div class="image-on-text-container bg-secondary">
    <span class="site-brand"></span>
  </div>
</div>

<p style="height: 100vh;">Scroll back up.....</p>

Javascript相关问答推荐

如何在alpinejs中显示dev中x-for的元素

为什么使用MAX_SAFE_INTEGER生成随机整数时数字分布不准确?

如何按预期聚合SON数据?

为什么我达到了时间限制!?LeetCode链接列表循环(已解决,但需要解释!)

成帧器运动中的运动组件为何以收件箱开始?

D3多线图显示1线而不是3线

如何从JSON数组添加Google Maps标记—或者如何为数组添加参数到标记构造器

. NET中Unix时间转换为日期时间的奇怪行为

在vercel throws上部署带有gunjs的sveltekit应用无法找到模块./' lib/文本编码'

TypeScript索引签名模板限制

如何粗体匹配的字母时输入搜索框使用javascript?

我可以使用空手道用户界面来获取网页的当前滚动位置吗?

对网格项目进行垂直排序不起作用

如何创建返回不带`new`关键字的实例的类

有条件重定向到移动子域

在我的index.html页面上找不到我的Java脚本条形图

使用auth.js保护API路由的Next.JS,FETCH()不起作用

打字脚本中方括号符号属性访问和拾取实用程序的区别

FireBase云函数-函数外部的ENV变量

MongoDB中的嵌套搜索