改变高度的百分比DIV背景颜色 [英] Change div background color on percentage of height
问题描述
我在做一个网站,在对方几个div和枝顶端的菜单。当你达到一个新的div,我想在菜单的背景颜色改变。我已经有这个脚本;
$(文件)。就绪(函数(){
变种scroll_pos = 0;
(文档)$ .scroll(函数(){
scroll_pos = $(本).scrollTop();
如果(scroll_pos> 2280){
$(#菜单),CSS(背景颜色,#6FC6DF')。
}其他{
$(#菜单),CSS(背景颜色,#B4B4B4')。
}
}
);
(文档)$ .scroll(函数(){
scroll_pos = $(本).scrollTop();
如果(scroll_pos> 3220){
$(#菜单),CSS(背景颜色,#B4B4B4')。
}
});
这工作得很好,但现在,我想使设计有求必应,我想的背景颜色改变对网站的百分比。这可能吗?
谢谢!
的$(document).scroll(函数(){
VAR scroll_pos = $(文件).scrollTop();
VAR docHeight = $(文件).height();
VAR百分比=(scroll_pos / docHeight);
无功红= Math.round(255 *百分比);
$(机构),CSS(背景颜色,RGBA('+红+',0,0,1)');
}
);
这是例子,如何使文档更红了低滚动。
您也可以实现的百分比映射到要显示一个十六进制值的函数:)
或者,如果你希望根据百分比变化:
的$(document).scroll(函数(){
VAR scroll_pos = $(文件).scrollTop();
VAR docHeight = $(文件).height();
变种百分比= Math.round((scroll_pos / docHeight)* 100);
如果(百分之> 33)
$(#菜单),CSS(背景颜色,#FF0000)。
}
);
I'm making a website with a couple of divs under each other and a menu which sticks to the top. When you reach a new div, I want the background color of the menu to change. I already have this script;
$(document).ready(function(){
var scroll_pos = 0;
$(document).scroll(function() {
scroll_pos = $(this).scrollTop();
if(scroll_pos > 2280) {
$("#menu").css('background-color', '#6FC6DF');
} else {
$("#menu").css('background-color', '#B4B4B4');
}
}
);
$(document).scroll(function() {
scroll_pos = $(this).scrollTop();
if(scroll_pos > 3220) {
$("#menu").css('background-color', '#B4B4B4');
}
});
This works fine, but now that I want to make the design responsive, I would like the background color to change on a percentage of the website. Is that possible?
Thanks!
$(document).scroll(function() {
var scroll_pos=$(document).scrollTop();
var docHeight=$(document).height();
var percent=(scroll_pos/docHeight);
var red=Math.round(255*percent);
$("body").css('background-color', 'rgba('+red+',0,0,1)');
}
);
An example how to make the document more red the lower you scroll. You can also implement a function that maps the percent to a hex value you wish to display :)
Or if you wish to change depending on percent:
$(document).scroll(function() {
var scroll_pos=$(document).scrollTop();
var docHeight=$(document).height();
var percent=Math.round((scroll_pos/docHeight)*100);
if (percent>33)
$("#menu").css('background-color', '#ff0000');
}
);
这篇关于改变高度的百分比DIV背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!