我正在尝试从起点开始制作一条垂直线(定义如下
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);
}
}
更新的小提琴
我没有完成它,但如果它有帮助,它几乎就在那里。它会动态计算出高度和开始/结束位置,你也许可以完成它,它没有很好地计算结束位置,一些调整,不过没关系。查看 JSfiddle;
https://jsfiddle.net/x4jhLohs/2/
$(document).on('ready', function() {
$(window).scroll(function(){
handleVerticalLine();
});
function handleVerticalLine() {
// Loop through and grab all our Vertical Line Containers, each one will have a Start and an End selector.
$('.vertical-line-container').each(function() {
// Grab our start and end elements.
var $startElement = $( $( this ).data( 'line-start-selector' ) );
var $endElement = $( $( this ).data( 'line-end-selector' ) );
var $verticalLine = $( this ).find( $( '.vertical-line' ) );
if( $startElement.length && $endElement.length && $verticalLine.length ) {
var startElementTopOffsfet = $startElement.offset().top;
var endElementTopOffsfet = $endElement.offset().top + $endElement.height();
var startElementVerticalLineBegin = startElementTopOffsfet;
var endElementVerticalLineBegin = endElementTopOffsfet;
$verticalLine.css( 'top', startElementTopOffsfet + $startElement.height() );
var verticalLinePercentage = startElementVerticalLineBegin / endElementVerticalLineBegin * 100;
verticalLinePercentage += $(window).scrollTop();
$verticalLine.css('height', verticalLinePercentage )
}
});
}
});