Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/423.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 偏移html锚点以调整固定标题_Javascript_Html_Css_Anchor_Offset - Fatal编程技术网

Javascript 偏移html锚点以调整固定标题

Javascript 偏移html锚点以调整固定标题,javascript,html,css,anchor,offset,Javascript,Html,Css,Anchor,Offset,我正在努力清理锚的工作方式。我有一个固定在页面顶部的标题,因此当您链接到页面中其他位置的锚定时,页面会跳转,因此锚定位于页面顶部,将内容保留在固定的标题后面(我希望这是有意义的)。我需要一种方法,使锚从收割台高度偏移25px。我更喜欢HTML或CSS,但Javascript也可以接受。对于同一问题,我使用了一个简单的解决方案:在每个锚点上放置一个40px的填充顶部。我发现了这个解决方案: 我的锚 这不会在内容上造成任何差距,锚定链接的效果非常好。正如@moeffju所建议的,这是可以做到的。

我正在努力清理锚的工作方式。我有一个固定在页面顶部的标题,因此当您链接到页面中其他位置的锚定时,页面会跳转,因此锚定位于页面顶部,将内容保留在固定的标题后面(我希望这是有意义的)。我需要一种方法,使锚从收割台高度偏移25px。我更喜欢HTML或CSS,但Javascript也可以接受。

对于同一问题,我使用了一个简单的解决方案:在每个锚点上放置一个40px的填充顶部。

我发现了这个解决方案:


我的锚

这不会在内容上造成任何差距,锚定链接的效果非常好。

正如@moeffju所建议的,这是可以做到的。我遇到的问题(我很惊讶我没有看到讨论)是使用填充或透明边框重叠前面的元素的技巧,防止在这些部分的底部悬停并单击操作,因为下面的操作在z顺序中更高

我找到的最佳修复方法是将节内容放在
div
中,该div位于
z-index:1

// Apply to elements that serve as anchors
.offset-anchor {
  border-top: 75px solid transparent;
  margin: -75px 0 0;
  -webkit-background-clip: padding-box;
  -moz-background-clip: padding;
  background-clip: padding-box;
}

// Because offset-anchor causes sections to overlap the bottom of previous ones,
// we need to put content higher so links aren't blocked by the transparent border.
.container {
  position: relative;
  z-index: 1;
}

我遇到了同样的问题,并最终手动处理单击事件,如:

$('#mynav a').click(() ->
  $('html, body').animate({
      scrollTop: $($(this).attr('href')).offset().top - 40
  }, 200
  return false
)

当然,滚动动画是可选的。

因为这是一个演示问题,所以纯CSS解决方案将是理想的。然而,这个问题是在2012年提出的,尽管已经提出了相对定位/负裕度解决方案,但这些方法似乎相当粗糙,会产生潜在的流问题,并且无法动态响应DOM/视口中的更改

考虑到这一点,我相信使用JavaScript仍然是(2017年2月)最好的方法。下面是一个普通的JS解决方案,它将响应锚定点击并在加载时解析页面哈希。如果需要动态计算,请修改
.getFixedOffset()
方法。如果您使用的是jQuery


我也在寻找解决办法。就我而言,这很容易

我有一个包含所有链接的列表菜单:

下面是它应该指向的标题

1
此处文本

二 此处文本

三 此处文本

四 此处文本

现在,因为我的页面顶部有一个固定的菜单,我不能让它进入我的标签,因为它会在菜单后面

取而代之的是,我将一个span标记放在具有正确id的标记内

1
现在使用两行CSS来正确定位它们

h3{位置:相对;}
h3 span{位置:绝对;顶部:-200px;}
更改顶部值以匹配固定收割台(或更多)的高度。
现在我假设这也适用于其他元素。

您可以在不使用任何javascript的情况下使用CSS

给你的主播上课:


然后,通过将锚定元素设置为块元素并对其进行相对定位,可以将其定位在高于或低于其在页面上实际显示位置的偏移量-250px将定位锚向上250px

a.anchor{
显示:块;
位置:相对位置;
顶部:-250px;
可见性:隐藏;
}

受亚历山大·萨文启发的纯css解决方案:

a[name] {
  padding-top: 40px;
  margin-top: -40px;
  display: inline-block; /* required for webkit browsers */
}
如果目标仍在屏幕外,您还可以选择添加以下内容:

  vertical-align: top;

@AlexanderSavin的解决方案在
WebKit
浏览器中对我来说非常有效

此外,我还必须使用伪类,该类将样式应用于所选锚点,以调整
FF
Opera
&
IE9

a:target {
  padding-top: 40px
}
请注意,此样式不适用于
Chrome
/
Safari
,因此您可能需要使用css黑客、条件注释等

我还想注意到,Alexander的解决方案之所以有效,是因为目标元素是
inline
。如果不需要链接,只需更改
display
属性即可:

<div id="myanchor" style="display: inline">
   <h1 style="padding-top: 40px; margin-top: -40px;">My anchor</h1>
</div>

我的锚
除了Ziav的答案(感谢Alexander Savin),我需要使用老式的
..
,因为我们在代码中使用
..
是为了另一个目的。我在使用
display:inline block
时遇到了一些显示问题——每个
元素的第一行都略微向右缩进(在Webkit和Firefox浏览器上)。最后我尝试了其他的
显示
值和
显示:表格标题
对我来说非常合适

.anchor {
  padding-top: 60px;
  margin-top: -60px;
  display: table-caption;
}

我在一个TYPO3网站上遇到了这个问题,所有的“内容元素”都用类似以下的东西包装:

<div id="c1234" class="contentElement">...</div>
固定顶杆为40px高,现在锚再次工作,并在顶杆下启动10px


这种技术的唯一缺点是您不能再使用
:target

我在我的每个
h1
元素之前添加了40px高度
.vspace
元素来固定锚点

<div class="vspace" id="gherkin"></div>
<div class="page-header">
  <h1>Gherkin</h1>
</div>

它工作得很好,空间也不拥挤。

改变位置属性的解决方案并不总是可行的(它会破坏布局),因此我建议:

HTML:

使用以下命令:

<a id="top">&nbsp;</a>

要最小化重叠,请将字体大小设置为1px。空锚在某些浏览器中不起作用。

您可以不用js,也不用修改html。它只是css。
这将在每个具有id的a标记之前附加一个伪元素。调整值以匹配标题的高度。

如何使用具有可链接id的隐藏跨度标记,以提供导航栏的高度:

#head1 {
  padding-top: 60px;
  height: 0px;
  visibility: hidden;
}


<span class="head1">somecontent</span>
<h5 id="headline1">This Headline is not obscured</h5>
#标题1{
填充顶部:60px;
高度:0px;
可见性:隐藏;
}
一些内容
这个标题没有被掩盖

问题是:

我一直面临着类似的问题,不幸的是,在实施了上述所有解决方案后,我得出了以下结论

  • 我的内部元素有一个脆弱的CSS结构,实现了位置相对/绝对播放,完全破坏了页面设计
  • CSS不是我的
    <div class="vspace" id="gherkin"></div>
    <div class="page-header">
      <h1>Gherkin</h1>
    </div>
    
    .vspace { height: 40px;}
    
    <a id="top">Anchor</a>
    
    #top {
        margin-top: -250px;
        padding-top: 250px;
    }
    
    <a id="top">&nbsp;</a>
    
    a[id]::before {
        content: '';
        display: block;
        height: 50px;
        margin: -30px 0 0;
    }
    
    #head1 {
      padding-top: 60px;
      height: 0px;
      visibility: hidden;
    }
    
    
    <span class="head1">somecontent</span>
    <h5 id="headline1">This Headline is not obscured</h5>
    
    <div id="#anchor"></div> <!-- #anchor here is the anchor tag which is on your URL -->
    
     $(function() {
      $('a[href*=#]:not([href=#])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
    && location.hostname == this.hostname) {
    
          var target = $(this.hash);
          target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
          if (target.length) {
            $('html,body').animate({
              scrollTop: target.offset().top - 125 //offsets for fixed header
            }, 1000);
            return false;
          }
        }
      });
      //Executed on page load with URL containing an anchor tag.
      if($(location.href.split("#")[1])) {
          var target = $('#'+location.href.split("#")[1]);
          if (target.length) {
            $('html,body').animate({
              scrollTop: target.offset().top - 125 //offset height of header here too.
            }, 1000);
            return false;
          }
        }
    });
    
    (text-indent:-99999px;)
    visibility: hidden;
    position:absolute;
    top:-80px;    
    
    function moveUnderNav() {
        var $el, h = window.location.hash;
        if (h) {
            $el = $(h);
            if ($el.length && $el.closest('table').length) {
                $('body').scrollTop( $el.closest('table, tr').position().top - 26 );
            }
        }
    }
    
    $(window)
        .load(function () {
            moveUnderNav();
        })
        .on('hashchange', function () {
            moveUnderNav();
        });
    
    a[name]:not([href]){
        display: block;    
        position: relative;     
        top: -100px;
        visibility: hidden;
    }
    
    :target {
        display: block;    
        position: relative;     
        top: -100px;
        visibility: hidden;
    }
    
    $(".dropdown-menu a[href^='#']").on('click', function(e) {
       // prevent default anchor click behavior
       e.preventDefault();
    
       // animate
       $('html, body').animate({
           scrollTop: $(this.hash).offset().top - 60
         }, 300, function(){
         });
    });
    
    [id]::before {
      content: '';
      display: block;
      height:      75px;
      margin-top: -75px;
      visibility: hidden;
    }
    
    #uberbar { 
        border-bottom:1px solid #0000cc; 
        position:fixed; 
        top:0; 
        left:0; 
        z-index:2000; 
        width:100%;
    }
    
    a.anchor {
        display: block;
        position: relative;
        visibility: hidden;
    }
    
    <script type="text/javascript">
    $(document).ready(function() {
        (function() {
            //settings
            var fadeSpeed = 200, fadeTo = 0.85, topDistance = 30;
            var topbarME = function() { $('#uberbar').fadeTo(fadeSpeed,1); }, topbarML = function() { $('#uberbar').fadeTo(fadeSpeed,fadeTo); };
            var inside = false;
            //do
            $(window).scroll(function() {
                position = $(window).scrollTop();
                if(position > topDistance && !inside) {
                    //add events
                    topbarML();
                    $('#uberbar').bind('mouseenter',topbarME);
                    $('#uberbar').bind('mouseleave',topbarML);
                    inside = true;
                }
                else if (position < topDistance){
                    topbarME();
                    $('#uberbar').unbind('mouseenter',topbarME);
                    $('#uberbar').unbind('mouseleave',topbarML);
                    inside = false;
                }
            });
            $('#content').css({'margin-top': $('#uberbar').outerHeight(true)});
            $('a.anchor').css({'top': - $('#uberbar').outerHeight(true)});
        })();
    });
    </script>
    
    <div id="uberbar">
        <!--CONTENT OF FIXED HEADER-->
    </div>
    ....
    <div id="content">
        <!--MAIN CONTENT-->
        ....
        <a class="anchor" id="anchor1"></a>
        ....
        <a class="anchor" id="anchor2"></a>
        ....
    </div>
    
    /*jslint browser: true, plusplus: true, regexp: true */
    
    function anchorScroll(fragment) {
        "use strict";
        var amount, ttarget;
        amount = $('header').height();
        ttarget = $('#' + fragment);
        $('html,body').animate({ scrollTop: ttarget.offset().top - amount }, 250);
        return false;
    }
    
    function outsideToHash() {
        "use strict";
        var fragment;
        if (window.location.hash) {
            fragment = window.location.hash.substring(1);
            anchorScroll(fragment);
        }
    }
    
    function insideToHash(nnode) {
        "use strict";
        var fragment;
        fragment = $(nnode).attr('href').substring(1);
        anchorScroll(fragment);
    }
    
    $(document).ready(function () {
        "use strict";
        $("a[href^='#']").bind('click',  function () {insideToHash(this); });
        outsideToHash();
    });
    
    // SCROLL ON CLICK
    // --------------------------------------------------------------------------
    $('.js-scroll').click(function(){
        var headerHeight = 60;
    
        $('html, body').animate({
            scrollTop: $( $.attr(this, 'href') ).offset().top - headerHeight
        }, 500);
        return false;
    });
    
    <div class="static-navbar">NAVBAR</div>
    <div class="scrollable-content">
      <p>Bla bla bla</p>
      <p>Yadda yadda yadda</p>
      <p>Mary had a little lamb</p>
      <h2 id="stuff-i-want-to-link-to">Stuff</h2>
      <p>More nonsense</p>
    </div>
    
    .static-navbar {
      height: 100px;
    }
    .scrollable-content {
      position: absolute;
      top: 100px;
      bottom: 0;
      overflow-y: scroll;
      width: 100%;
    }
    
        (function($, window) {
            var adjustAnchor = function() {
    
                var $anchor = $(':target'),
                        fixedElementHeight = 100;
    
                if ($anchor.length > 0) {
    
                    $('html, body')
                        .stop()
                        .animate({
                            scrollTop: $anchor.offset().top - fixedElementHeight
                        }, 200);
    
                }
    
            };
    
            $(window).on('hashchange load', function() {
                adjustAnchor();
            });
    
        })(jQuery, window);
    
    $('html, body')
         .stop()
         .animate({
             scrollTop: $anchor.offset().top - fixedElementHeight
         }, 200);
    
    window.scrollTo(0, $anchor.offset().top - fixedElementHeight);
    
     !function(o,n){var t=function(){var n=o(":target"),t=100;n.length>0&&o("html, body").stop().animate({scrollTop:n.offset().top-t},200)};o(n).on("hashchange load",function(){t()})}(jQuery,window);