【发布时间】:2022-01-15 17:10:39
【问题描述】:
我有一个聊天或转到顶部带有白色边框的 svg btn,我的一些部分元素有蓝色和其他白色背景
我想要做的是当固定 btn 在滚动时进入该部分时检查其背景 并在每种情况下添加不同的类。 我怎样才能在 javascript 或 jquery 中做到这一点?
谢谢
【问题讨论】:
标签: javascript html jquery css scroll
我有一个聊天或转到顶部带有白色边框的 svg btn,我的一些部分元素有蓝色和其他白色背景
我想要做的是当固定 btn 在滚动时进入该部分时检查其背景 并在每种情况下添加不同的类。 我怎样才能在 javascript 或 jquery 中做到这一点?
谢谢
【问题讨论】:
标签: javascript html jquery css scroll
如果你必须在不同的部分改变颜色,有几种方法可以做到,没有一种是容易的,只有少数会有很好的性能。
fixed 按钮的背景设为默认颜色。.button 变为 .button.red
data-attribute 示例:<section change-button-bg="red">
on load
.querySelectorAll(*[change-button-bg]),这样你就可以运行了
检查每个部分。currentTarget的全局变量
.isIntersecting 的回调函数做一些事情。
currentTaget 变量bounds.bottom 或 currentTarget 以查看它应该是哪种颜色。window.addEventListener('load', (event) => {
const changeBG = document.querySelectorAll('*[change-button-bg]');
let currentTarget = null;
const Observer = new IntersectionObserver((entries, Observer) => {
for (const entry of entries) {
if (entry.isIntersecting) {
currentTarget = entry.target;
addColor(true);
window.addEventListener('scroll', watchTarget);
} else {
addColor(false);
window.removeEventListener('scroll', watchTarget)
}
}
}, {threshold: 0.15});
for (const element of changeBG) {
Observer.observe(element);
}
function watchTarget() {
const bounds = currentTarget.getBoundingClientRect();
if (bounds.bottom < window.innerHeight - 80) {
addColor(false);
} else {
addColor(true);
}
}
function addColor(add) {
const btn = document.getElementById('button');
if (add) {
btn.classList.add('red');
} else {
btn.classList.remove('red');
}
}
});
body {
margin: 0;
}
section {
width: 100vw;
height: 100vh;
background: red;
}
section:nth-child(even) {
background: blue;
}
button {
position:fixed;
right: 50px;
bottom: 50px;
padding: 15px 25px;
border: none;
color: white;
background-color: blue;
cursor: pointer;
}
button.red {
background-color: red;
}
<html>
<body>
<section></section>
<section change-button-bg="red"></section>
<section></section>
<section change-button-bg="red"></section>
<section></section>
<button id="button">Top</button>
</body>
</html>
【讨论】:
这是我正在寻找的解决方案,我使用 Intersection Observer 完成了它
document.addEventListener('DOMContentLoaded',()=>{
let options = {
root:null,
rootMargin:"-570px 0px -100px 0px",
threshold:0.05
};
let Observer= new IntersectionObserver(changColor,options);
document.querySelectorAll("section").forEach(section => {
Observer.observe(section);
});
});
function changColor(elements) {
elements.forEach(el => {
if (el.isIntersecting) {
let elbg=el.target.dataset.bg;
if (elbg=="blue") { //if section data-bg== blue
// change svg button style
document.getElementById("chatting_path_7").style.fill = "#fff";
document.getElementById("to_top_Ellipse_4").style.stroke = "#fff";
} else {
document.getElementById("chatting_path_7").style.fill = "#034ea2";
document.getElementById("to_top_Ellipse_4").style.stroke = "#034ea2";
}
}
})
}
【讨论】: