【问题标题】:jQuery animate on scroll backgroundColor not changing滚动背景颜色上的jQuery动画不改变
【发布时间】:2016-03-12 09:29:53
【问题描述】:
我的小提琴:https://jsfiddle.net/jzhang172/owkqmtcc/5/
我想要完成的事情:当我在 div 中的任意位置滚动时,div“内容”的背景颜色会发生变化。当滚动停留在 div 的顶部时,它会恢复到原来的颜色。当我添加高度而不是背景颜色时,它工作正常,但不确定为什么背景颜色不起作用:
$(function(){
var content = $(".content");
$(".box").scroll(function(event){
var positionofscroll = $(".content").scrollTop();
if(positionofscroll == 0){
content.stop().animate({
backgroundColor:"rgba(105, 63, 63, 0.69)"
},500);
}else {
content.stop().animate({
backgroundColor:"red"
},500);
}
}); //scroll
});
.box{
width:100%;
height:500px;
background:gray;
overflow:auto;
}
.content{
color:white;
display:flex;
justify-content:center;
align-items:center;
height:1000px;
background:red;
font-size:30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<!--Shadow Box when user scrolls -->
<div class="box">
<div class="content">
I'm content
</div>
</div>
【问题讨论】:
标签:
javascript
jquery
html
css
【解决方案1】:
尝试包含 jQuery UI ,因为 .animate() 在没有修改或颜色插件的情况下不会为颜色设置动画;见.animate()
动画属性和值
所有动画属性都应该动画成一个单个数字
值,除非下文另有说明;大多数非数字属性
无法使用基本的 jQuery 功能进行动画处理(例如,
width、height 或 left 可以设置动画,但 background-color
不能,除非使用了jQuery.Color 插件)。
还将positionofscroll处的选择器调整为$(this).scrollTop();在if处将比较运算符更改为>
$(function() {
var content = $(".content");
$(".box").scroll(function(event) {
var positionofscroll = $(this).scrollTop();
console.log(positionofscroll);
if (positionofscroll > 0) {
content.stop().animate({
backgroundColor: "rgba(105, 63, 63, 0.69)"
}, 500);
} else {
content.stop().animate({
backgroundColor: "red"
}, 500);
}
}); //scroll
});
.box {
width: 100%;
height: 500px;
background: gray;
overflow: auto;
}
.content {
color: white;
display: flex;
justify-content: center;
align-items: center;
height: 1000px;
background: red;
font-size: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0-beta.1/jquery-ui.min.js"></script>
<!--Shadow Box when user scrolls -->
<div class="box">
<div class="content">
I'm content
</div>
</div>
【解决方案2】:
试试这个:
var content = $(".content");
$(".box").scroll(function(event)
{
var positionofscroll = $(this).scrollTop();
if (positionofscroll > 0)
{
$(".content").css('background-color','rgba(105, 63, 63, 0.69)');
}
else
{
$(".content").attr('style','');
}
});
小提琴:https://jsfiddle.net/4fc6pook/
如果你想动画背景颜色的变化,在.content中添加一些css:
transition: all 0.3s ease-out;
或类似的东西。
希望这会有所帮助!