这个问题的某些部分已经涵盖了here。
我正在尝试创建一个导航栏,它位于所有元素之上,如下所示:
<div class="navbar">
...links...
</div>
<div class="hero-with-image">
<h1>Hello</h1>
</div>
然后如果我的英雄是黑暗或在背景上有图像,则反转导航链接。当你滚动幻灯片时,Squarespace在他们的主页上有一个很好的例子。
我使用Ruby On Rails作为我的后端,我找到的解决方案之一是为我的导航栏创建一个帮助方法,在那里我定义我的controller.controller_name && controller.action_name
然后在我的html标签中添加一个额外的类.has-dark-background
。但是如果我有多个深色背景页面和多页浅背景,有什么办法可以使用jQuery基于英雄对象反转文本颜色?
这是我发现的jquery的一个很好的解决方案:
var rgb = [255, 0, 0];
// randomly change to showcase updates
setInterval(setContrast, 1000);
function setContrast() {
// randomly update
rgb[0] = Math.round(Math.random() * 255);
rgb[1] = Math.round(Math.random() * 255);
rgb[2] = Math.round(Math.random() * 255);
// http://www.w3.org/TR/AERT#color-contrast
var o = Math.round(((parseInt(rgb[0]) * 299) +
(parseInt(rgb[1]) * 587) +
(parseInt(rgb[2]) * 114)) / 1000);
var fore = (o > 125) ? 'black' : 'white';
var back = 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';
$('#bg').css('color', fore);
$('#bg').css('background-color', back);
}
上面的代码工作正常,但它只能基于当前对象背景的文本颜色。
换句话说,我不想创建多个导航栏,我只想根据内容(英雄)背景颜色反转颜色。
有没有基于Jquery或Ruby on Rails的其他解决方案?
请原谅我的英语不好。谢谢你的帮助和时间。
这接近你想要的吗?
div {
width: 200px;
height: 200px;
}
.text {
mix-blend-mode: difference;
color: white;
}
.wrapper {
background: url(http://lorempixel.com/400/400/);
}
<div class="wrapper">
<div class="text">This is my text, hellow World! This is my text, hellow World! This is my text, hellow World! This is my text, hellow World!</div>
</div>
这是我想出的答案。我为导航栏创建了一个帮助方法:
# helpers/application_helper.rb
def color_attr
if %w(pages).include?(params[:controller])
return 'has-dark-background'
end
end
其中%w(pages)
是控制器名称。然后,我在header
标签中使用了我的助手:
# haml syntax
%header(class="#{color_attr} other-classes" role="banner")
类has-dark-background
手动将文本颜色更改为带有其他样式的白色,而默认颜色为黑色。不幸的是,这种方法不会动态地改变文本颜色。
不确定这是否是最佳方式,但这是另一种方式:
# about.html.erb
- content_for :navbar_class, 'new_class_1 new_class_2 ...'
# _navbar.html.erb
...
%header(id="navbarPrimary" class="navbar #{content_for :navbar_class}" role="navigation")
...