你能用JavaScript设置一个max-background-size吗?



当用户向下滚动页面时,我使用普通JS来增加background-size值,以创建视差滚动效果。我的功能如下:

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之前停止增长。

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

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;
}
} 
});

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

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;
}

最新更新