我已经成功设计了页面 anchor ,它将在第一次单击时补偿固定的标题高度,代码如下:
<p id="anchorid" style="padding-top: 287px; margin-top: -287px; width: 20px;">
FILLER TEXT
</p>
我遇到的问题是,当您滚动时,我的标题会缩小,因此一旦您通过 anchor 单击页面,下次您在该页面上单击该页面的 anchor 时,填充就会超过-补偿(因为它被设置为初始标题高度)并且该部分被带到页面的中间而不是顶部。我希望做的是将 anchor 填充动态设置为标题的高度,以便它始终将该部分带到顶部,但不幸的是我不知道如何做到这一点。
有没有办法使用 anchor (id =“filler”)让浏览器滚动到某个点,具体取决于标题的高度,使用CSS?
类似的问题在这里解决,但它们的标题没有改变大小:HTML position:fixed page header and in-page anchors
最佳答案
编辑答案:
这是我用于固定 header 的代码,该代码在使用 jQuery 通过 smouth 滚动滚动到 anchor 时负责处理偏移量。
这是一个插图:https://jsfiddle.net/mmb5k7xb/1/
要查看脚本对不同高度的 react ,只需更改 html 部分中菜单高度的值即可。
希望有帮助。
<script type="text/javascript">
var $ = jQuery.noConflict();
$(document).ready(function($) {
var menu_height = $('.menu').height(); // calulate the height of the menu
(function(document, history, location) {
var HISTORY_SUPPORT = !!(history && history.pushState);
var anchorScrolls = {
ANCHOR_REGEX: /^#[^ ]+$/,
OFFSET_HEIGHT_PX: menu_height, // Set the offset with the dynamic value
/**
* Establish events, and fix initial scroll position if a hash is provided.
*/
init: function() {
this.scrollIfAnchor(location.hash);
$('body').on('click', 'a', $.proxy(this, 'delegateAnchors'));
},
/**
* Return the offset amount to deduct from the normal scroll position.
* Modify as appropriate to allow for dynamic calculations
*/
getFixedOffset: function() {
return this.OFFSET_HEIGHT_PX;
},
/**
* If the provided href is an anchor which resolves to an element on the
* page, scroll to it.
* @param {String} href
* @return {Boolean} - Was the href an anchor.
*/
scrollIfAnchor: function(href, pushToHistory) {
var match, anchorOffset;
if(!this.ANCHOR_REGEX.test(href)) {
return false;
}
match = document.getElementById(href.slice(1));
if(match) {
anchorOffset = $(match).offset().top - this.getFixedOffset();
$('html, body').animate({ scrollTop: anchorOffset});
// Add the state to history as-per normal anchor links
if(HISTORY_SUPPORT && pushToHistory) {
history.pushState({}, document.title, location.pathname + href);
}
}
return !!match;
},
/**
* If the click event's target was an anchor, fix the scroll position.
*/
delegateAnchors: function(e) {
var elem = e.target;
if(this.scrollIfAnchor(elem.getAttribute('href'), true)) {
e.preventDefault();
}
}
};
$(document).ready($.proxy(anchorScrolls, 'init'));
})(window.document, window.history, window.location);
});
</script>
关于HTML 位置 :fixed variable-height page header and in-page anchors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36066305/