CSS change color on scroll / cut text - overflow z-index
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
This one is maybe a big riddle. Maybe its not. I want to change the color of a position:fixed menu when scrolling.
My first intention was to use two fixed menus and overflow:hidden but it doesnt work on fixed elements. My second try was using z-index. But it seems impossible.
Maybe someone has an idea?
回答1:
What you are looking for is clipping. This allows you to specify a rectangular region where an element is visible.
You can use:
clip: rect(auto, auto, auto, auto);
on the container to emulate overflow: hidden for the position: fixed menu, so you can crop the text as you scroll.
Note that while clip is deprecated, the new clip-path does not work with position: fixed elements, so you are stuck with clip for now.
clip requires absolute or fixed positioning, but you can easily work around that problem by placing a position: absolute element inside a position: relative container, like so:
The behaviour you are looking for is the same as background-attachement:fixed;.
Although this solution is pretty simple and doesn't rely on JS, from a sematic point of view it shouldn't be recommended.
The point is to use 2 background images with background-attachement: fixed; and to position the link over them for interaction. It will give you the desired behaviour with a smooth color change according to the background color :
EDIT: proven that it does NOT work on Firefox, so probably this is just a Chrome quirk, still interesting behaviour so I'll leave this answer if anyone just wants to build a Chrome only implementation or when Firefox and other browsers come along.
You can use relative parents with overflow to mimic the effect of the changing color.
Downside: you have to duplicate your menu (which is semantically well, just plain wrong). You could use some basic javascript to do the duplication of the menu though, that would improve it a little. I also only tested this on Chrome, but it seems really basic CSS so I imagine this will work on any browser / device.
If you don't want to have to manage duplicate elements to pull off this effect with CSS clip as per Antony's solution, then you can use a couple jQuery plugins:
jq-clipthru - This is a superflexible plugin that can probably do everything you want (and a lot more), but it also requires the jQuery UI library. [Demo]
Unobscure Text - This is my very lightweight plugin that has a very specific use case, but it's not compatible with jQuery 3. [Demo]
If you require jQuery 3 support and don't care for IE 11 and below, then you can use a solution based on SVG clip-path, like this.