【问题标题】:Changing picture according to amount of scroll or text id根据滚动量或文本ID更改图片
【发布时间】:2021-03-05 07:34:05
【问题描述】:

(请不要使用 jQuery,只有 Javascript)

您好,我是 Javascript 新手,我想知道是否可以制作一个固定图像,在滚动过程中将其替换为同一位置的另一个图像。这样,当您滚动时,图片看起来会发生变化。

我找到了一个使用 jQuery 的答案,但我不知道它是什么意思,因为我们不应该在课堂上使用那种语言。

https://levelup.gitconnected.com/how-to-create-frame-by-frame-moving-image-on-scroll-effect-30ce577c63c2

// Global variable to control the scrolling behavior
const step = 30; // For each 30px, change an image
function trackScrollPosition() {
  const y = window.scrollY;
  const label = Math.min(Math.floor(y/30) + 1, 20);
  const imageToUse = fruitImages[label];
  // Change the background image
  $('.image-container').css('background-image', `url('${imageToUse}')`);
}
$(document).ready(()=>{
  $(window).scroll(()=>{
    trackScrollPosition();
  })
})

我可以理解链接中的教程,但这部分我根本不明白。懂jQuery的人可以把它翻译成Javascript吗?这将是对我最大的帮助。

【问题讨论】:

    标签: javascript html jquery image scroll


    【解决方案1】:

    纯 JS 中的相同脚本

    // Global variable to control the scrolling behavior
    const step = 30; // For each 30px, change an image
    function trackScrollPosition() {
      const y = window.scrollY;
      const label = Math.min(Math.floor(y/30) + 1, 20);
      const imageToUse = fruitImages[label];
      // Change the background image
      document.querySelector('.image-container').style.backgroundImage = `url(${imageToUse})`;
    }
    window.addEventListener("load",function() {
      window.addEventListener('scroll',trackScrollPosition);
    })
    

    【讨论】:

      【解决方案2】:

      $('.image-container').css('background-image', 'url('${imageToUse}')') - 这部分意味着我们正在寻找一个具有 image-container 类的元素,并且我们正在将它的 css background-image 属性更改为 imageToUse(之前设置为 fruitImages[label])。

      $(document).ready(()=>{
        $(window).scroll(()=>{
          trackScrollPosition();
        })
      })
      

      一旦文档对象模型 (DOM) 变得可以安全操作,上面的函数就会运行,并负责在滚动时调用 trackScrollPosition 函数。

      【讨论】:

      • 这不是 OP 要求的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-22
      • 1970-01-01
      • 2020-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多