我想要滚动时
background: linear-gradient
颜色的平滑过渡。它在 Chrome 中运行良好,但在 Firefox 中转换是瞬时的。我不知道我做错了什么
滚动时,将 div 的类从
item-static
更改为 item-sticky
。
// Initial state
const target = document.getElementsByClassName("target");
const w_width = 651;
var scrollPos = 0;
changeTargetClass();
checkWindowSize();
window.addEventListener('resize', checkWindowSize);
function checkWindowSize() {
if (window.innerWidth > w_width) {
// adding scroll event
window.addEventListener('scroll', changeTargetClass);
} else {
window.removeEventListener('scroll', changeTargetClass);
target[0].classList.add('static-item')
}
}
function changeTargetClass() {
scrollPos = (document.body.getBoundingClientRect()).top;
setupTarget()
}
function setupTarget() {
if (scrollPos >= 0) {
target[0].classList.add('static-item')
target[0].classList.remove('sticky-item')
} else {
target[0].classList.remove('static-item')
target[0].classList.add('sticky-item')
}
}
@property --myColor1 {
syntax: '<color>';
initial-value: rgba(85, 85, 249, 1);
inherits: false;
}
@property --myColor2 {
syntax: '<color>';
initial-value: rgb(255, 255, 255);
inherits: false;
}
.target {
top: 0;
}
.flex-container {
display: flex;
align-items: center;
justify-content: space-between;
top: 0;
z-index: 3;
background: white;
}
.sticky-item {
position: sticky;
--myColor1: rgb(255, 255, 255);
--myColor2: rgb(255, 255, 255);
transition: --myColor1 1s ease-in-out, --myColor2 1s ease-in-out;
background: linear-gradient(180deg, var(--myColor1) 0%, var(--myColor2) 100%);
}
.static-item {
position: static;
--myColor1: rgba(85, 85, 249, 1);
--myColor2: rgb(255, 255, 255);
transition: --myColor1 1s ease-in-out, --myColor2 1s ease-in-out;
background: linear-gradient(180deg, var(--myColor1) 0%, var(--myColor2) 100%);
}
<div class="target static-item"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Sapiente alias quod ullam non</div>
<div class="big-box" style="height: 120vh; background: black;"></div>
您在 Firefox 中遇到的问题可能源于其处理过渡属性中的 CSS 自定义属性(--myColor1 和 --myColor2)。
看来 Firefox 可能不完全支持您定义的自定义属性的转换。
您可以转换 .target 元素的不透明度,而不是直接转换自定义属性,这会间接转换自定义属性定义的颜色。这种方法往往会得到更广泛的跨浏览器支持。
<style>
.target {
transition: opacity 1s ease-in-out; /* Add opacity transition */
}
.sticky-item {
opacity: 1; /* Ensure element is visible when sticky */
}
.static-item {
opacity: 0; /* Hide element when static */
}
</style>