繁体   English   中英

如何使用香草 Javascript 动态更改内联 SVG 的颜色?

[英]How to dynamically change the colour of an inline SVG using vanilla Javascript?

我有一个简单的内联 SVG 徽标,全黑,在我的 CSS 中我可以调整颜色,但是,我想知道如何在用户向下滚动页面时动态更改徽标的颜色。 让我详细说明...

所以我有一个简单的网站,它在任何给定页面上由两个部分组成,顺序各不相同,一个部分有黑色背景和白色文本,另一个,你猜对了,白色背景和黑色文本。 我有一个 class 分别分配给每个部分的暗和亮。 当用户从深色部分滚动到浅色部分(反之亦然)时,我希望切换适当的徽标颜色。

我想知道是否有人可以让我走上正确的轨道,如何使用 vanilla JS 做到这一点?

更新:这不是具体如何编辑 SVG 颜色,它更多的是关于如何使用 JS 来确定区域何时滚动到并更改 SVG 在该部分从暗变为亮或反之亦然。

谢谢

如果您能够 select 这些部分并且您知道哪些部分是深色或浅色,那么您可以使用滚动事件检查目标元素(svg)是否在特定部分内并根据您更改的该部分的背景(类) svg 元素的 class。

 function offset(element) { const bodyRect = document.body.getBoundingClientRect() const elemRect = element.getBoundingClientRect() return elemRect.top - bodyRect.top; } function handler(event) { const header = document.querySelector('.logo'); const dark = document.querySelectorAll('.dark-section'); const headerOffset = offset(header) const headerHeight = header.clientHeight; const check = [...dark].some(section => { const sectionOffset = offset(section); const sectionHeight = section.clientHeight; const topCheck = headerOffset + headerHeight / 2 >= sectionOffset; const bottomCheck = headerOffset + headerHeight / 2 < sectionOffset + sectionHeight if (topCheck && bottomCheck) { return true } }) if (check) { header.classList.add('light') header.classList.remove('dark') } else { header.classList.add('dark') header.classList.remove('light') } } ['scroll', 'resize'].forEach(function(e) { window.addEventListener(e, handler); });
 body, html { margin: 0; padding: 0; } header { height: 50px; position: fixed; background: rgba(51, 51, 5, 0.25); left: 0; top: 0; width: 100%; } svg { height: 50px; width: 50px; } section { min-height: 100vh; } section.dark-section { background: black; }.light circle { fill: white; transition: all 0.2s ease-in; }.dark circle { fill: black; transition: all 0.2s ease-in; }
 <header> <svg class="logo"> <circle fill="white" cx="50%" cy="50%" r="15"/> </svg> </header> <section class="dark-section"></section> <section></section> <section class="dark-section"></section> <section></section>

您也可以使用mix-blend-mode: difference ,但 svg 的颜色将取决于该部分的颜色,因此您不能仅将其设置为更改为特定颜色。

 body, html { margin: 0; padding: 0; } section { height: 100vh; background-color: white; } section.dark-section { background-color: black; } header { mix-blend-mode: difference; width: 100%; position: fixed; background: none; border: none; padding: 0; top: 0; left: 0; } svg { position: absolute; top: 0; left: 0; width: 50px; height: 50px; }.light-svg { display: block; }.dark-svg { display: none; }
 <header> <svg class="logo"> <circle fill-rule="nonzero" fill="#FFFFFF" cx="50%" cy="50%" r="15"/> </svg> </header> <section class="dark-section"></section> <section></section> <section class="dark-section"></section> <section></section>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM