javascript - 滚动后将元素固定到底部

标签 javascript jquery html css

我有一个反向滚动网站

<div class="end"></div>
<div class="wrapper">
<div class="ruler"><div class="currentheight">asd</div></div>
<div class="main"></div>
<div class="content">

<div class="high" id="high"><img src="placeholder.png"></img><h3>1.9km –  THIS HIGH! </h3></div>
<div class="washington"><a id="washington" class="btn btn-2 btn-2c" href="#high">Keep Going</a><img src="placeholder.png"></img><h3>0.15km – Washington Monument  </h3></div>
<div class="spacer"></div>

</div>
</div>

<div class="ep">
<a href="#washington" class="btn btn-2 btn-2c">START</a>
<h1>Title</h1>
<h2>content</h2>
</div>


$(function() {  $('html, body').scrollTop($(document).height() - $(window).height());});

元素 currentheight 在标尺部分的底部垂直对齐 - 当用户向上滚动时如何将其固定到页面底部,以便它始终保持可见?

fiddle :https://jsfiddle.net/koteva/5ug7pkte/

最佳答案

当窗口向上滚动元素时,您可以向当前高度元素添加“固定”类。您需要获取窗口的高度和元素的底部偏移量。您可以这样实现:

CSS:

.currentheight.fixed {position:fixed;bottom:38px;left:0px;background:rgba(0,0,8,1);width:calc(33% - 42px);}

JS:

//to start at bottom of page
$(function () { $('html, body').scrollTop($(document).height() - $(window).height()); });

// Store the bottom offset of currentheight element so that we don't recalculate at every scroll event
var elemBottomOffset;

//scrolling animations
$(document).ready(function () {
    $('a[href^="#"]').on('click', function (e) {
        e.preventDefault(); var target = this.hash; var $target = $(target);
        $('html, body').stop().animate({ 'scrollTop': $target.offset().top },
         1200, 'easeInOutQuart', function () { window.location.hash = target; });
    });
    // Calculate the bottom offset of currentheight element only once
    elemBottomOffset= $('.currentheight').offset().top + $('.currentheight').outerHeight();
});

$.fn.calc_height = function () {

    var window_scroll_top = $(window).scrollTop();
    var window_scroll_top_cm = window_scroll_top * 0.026458333;
    $('.currentheight').html(window_scroll_top_cm.toFixed(2) + ' cm');
    // Code to add fixed class based on window scrolling
    if (window_scroll_top + $(window).height() < elemBottomOffset)
        $('.currentheight').addClass('fixed');
    else
        $('.currentheight').removeClass('fixed');
};

//counter that needs to be positioned
$(function () {
    $.fn.calc_height();
    $(window).bind('scroll', function () {
        $.fn.calc_height();
    });
});

JSFiddle:https://jsfiddle.net/5ug7pkte/6/

关于javascript - 滚动后将元素固定到底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31990222/

相关文章:

javascript - css:框的切 Angular

javascript - Google api v3 在客户道路上显示附近的标记

javascript - 如何使用 array_merge 在 PHP/Highcharts 中显示非引用命令?

html - Mailchimp Outlook 条件 CSS 未生效

javascript - Stateful 和 Functional 无状态组件

javascript - 单击屏幕中央的打开图像

javascript - 数据表 - 使用 fnCreatedRow 添加详细信息行

javascript - 对 ie6 用户隐藏 CSS 和 HTML?

javascript - 选中复选框时禁用表单字段

javascript - HTML 页面上的多个 (14) 倒计时不起作用