我试图根据窗口中可见的高度(高度方式)来更改DIV的不透明度。例如,如果50%的DIV在窗口中可见,则不透明度应为.5
这就是我所拥有的,我知道它是业余的,而不是最佳代码。这是我的数学问题。当DIV在屏幕上大约50%时,我的计算结果大约为80%
$(window).scroll(function () {
var block = $('.block')
var blockHeight = block.outerHeight();
var bottom_of_block = block.offset().top + blockHeight;
var blockOpacity = 0;
if (bottom_of_block < ($(window).height() + $(window).scrollTop())) {
// Sets opacity to 1 if div is completely on screen
blockOpacity = 1;
} else {
// This is the math that I cant figure out completely
blockOpacity = ($(window).height() + $(window).scrollTop()) / (bottom_of_block);
}
block.css('opacity', blockOpacity);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height: 500px"></div>
<div class="block" style="background: blue;height: 220px;width: 220px;"></div>
&#13;
答案 0 :(得分:1)
我认为您需要像这样计算blockOpacity
:
blockOpacity = ($(window).height() + $(window).scrollTop() - block.offset().top) / blockHeight;