【问题标题】:Can you set a max-background-size with JavaScript?你能用 JavaScript 设置最大背景大小吗?
【发布时间】:2021-10-23 07:32:28
【问题描述】:

当用户向下滚动页面以创建视差滚动效果时,我正在使用 vanilla JS 来增加背景大小值。我的功能如下:

const heroBg = document.getElementById('hero');
window.addEventListener( 'scroll', function() {
    while (heroBg.style.backgroundSize <= '100') {
        heroBg.style.backgroundSize = 85 + window.pageYOffset/8 + '%';
        console.log(heroBg.style.backgroundSize);
        if (heroBg.style.backgroundSize === '100') {
            console.log('too big');
            break;
        }
    } 
});

我遇到的问题是 while 循环似乎只运行一次,并且图像在“backgroundSize”达到 100 之前就停止了增长。

【问题讨论】:

  • 你在哪里设置初始 heroBg backgroundSize 以及它设置的值是什么,是否有理由将 100 放在引号中?您需要提取数字。

标签: javascript html css while-loop


【解决方案1】:

如果使用字符串,则无法检查 &lt;=。此外,您不能添加数字和字符串;你必须使用括号。

const heroBg = document.getElementById('hero');
window.addEventListener( 'scroll', function() {
    while (parseInt(heroBg.style.backgroundSize) <= 100) {
        heroBg.style.backgroundSize = (85 + window.pageYOffset/8) + '%';
        console.log(heroBg.style.backgroundSize);
        if (parseInt(heroBg.style.backgroundSize) == 100) {
            console.log('too big');
            break;
        }
    } 
});

【讨论】:

    【解决方案2】:

    背景大小属性有度量单位,例如px或%,但它也是一个文本属性,要进行比较操作,需要先去掉度量单位,然后转换为a数字。我建议考虑另一种选择来执行上述任务

        const $body = document.querySelector("body");
        let viewportHeight = document.documentElement.clientHeight
    
        const bgSize = _ => $body.style.backgroundSize = `${(document.documentElement.scrollTop + viewportHeight) / document.documentElement.offsetHeight * 100 * (viewportHeight / 100)}px`
        bgSize()
        window.addEventListener("resize", _ => {
          viewportHeight = document.documentElement.clientHeight
          bgSize()
        })
        document.addEventListener("scroll", _ => {
            bgSize()
        })
        * {
            padding: 0;
            margin: 0;
            box-sizing: border-box;
        }
    
        body {
            height: 300vh;
            background: radial-gradient(closest-side circle, black 0% 100%, transparent 100%);
            background-repeat: no-repeat;
            background-position: center;
            background-attachment: fixed;
        }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-04
      • 2014-06-05
      相关资源
      最近更新 更多