我正在尝试制作一条从起点开始的垂直线(由
定义CSS) 到终点(我还没有定义)。
这个想法是; 用户滚动并且线条保持粘滞和/或增加高度直到终点。
但我不知道应该应用哪种逻辑。
(不工作)示例:https://jsfiddle.net/uzegqn7f/
例如,该行应该转到用户滚动位置后第二张图片的顶部。
<div class="vertical-line line-1"></div>
<img src="https://dummyimage.com/900x300/000000/fff.jpg" alt="" class="line-1-start">
<div class="content"></div>
<img src="https://dummyimage.com/900x300/000000/fff.jpg" alt="" class="line-1-end">
.content {
height:1000px;
}
img {
max-width:100%;
height:auto;
}
.vertical-line {
display: block;
position: absolute;
background: #ee403d;
width: 4px;
height: 10px;
z-index: 999;
}
.line-1 {
margin-left:10%;
margin-top:100px;
}
var distance = $('.line-1-end').offset().top - $('.line-1-start').offset().top;
function line_animation(element,distance) {
$(window).scroll(function(){
element.css("height", distance+"px");
});
}
$(document).on('load resize', function() {
var line1 = $(".line-1");
line_animation(line1,distance);
});
注意:
- 元素之间的距离并不总是相同的,可能会因响应而异。
最佳答案
试试这个(代码中的注释):
var start = $('.line-1-start').offset().top, // get where line starts
end = $('.line-1-end').offset().top, // get where line ends
line = $('#line');
drawLine($(window).scrollTop()); // draw initial line
$(window).scroll(function(){
drawLine($(this).scrollTop()); // draw line on scroll
});
$(document).on('resize', function() { // reset top and bottom and redraw line on window resize
start = $('.line-1-start').offset().top;
end = $('.line-1-end').offset().top;
drawLine($(window).scrollTop());
});
function drawLine(currentPosition) {
if (currentPosition >= start && currentPosition <= end) {
var distance = currentPosition - start;
line.css("height", distance+"px");
} else {
line.css("height", 0);
}
}
关于javascript - 根据起点和终点改变 div 高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41856588/