【问题标题】:implementing smooth scrolling while leaving :target css animations functional离开时实现平滑滚动:target css动画功能
【发布时间】:2016-01-20 03:45:11
【问题描述】:

我正在尝试实现平滑滚动,同时保留 css :target 动画的圆滑和锚链接功能。

我相信问题出在 :target 状态被 js 操纵,从而覆盖了 css 动画。为了引起对选定部分标题的注意,我在 :target 上稍微更改了填充,如下所示:

html

<section id="part_main">   
    <div class="text_box">
        <h1>To <a href="#">Section</a></h1>
    </div >
</section>

...

<section id="#">
    <div class="text_box">
        <h2>Headline Animation through Target</h2>
        <h3>body copy</h3>
    </div>
</section>

css

@-webkit-keyframes target {
    from {  padding-left: 0px;  } 
    50% {   padding-left: 20px; }
    to {    padding-left: 0px;  }
    }

:target div h2 {
    -webkit-animation-name:target;
    -webkit-animation-duration:3s;
    -webkit-animation-iteration-count:1;
    -webkit-animation-direction:linear;
}

它就像我想要的那样作为动画工作,除了锚链接当然会导致页面跳转而不是平滑滚动动作。添加时出现问题:

js

<script>
        $('a[href*=#]:not([href=#])').click(function(e) {
            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
            }, 1000);
            return false;
        }
    }
});

试图使页面过渡更平滑。我曾尝试使用其他 jQuery 插件来操作页面位置,但遗憾的是无济于事(而且我没有 js // jQuery 经验)。我会珍惜任何帮助或提示,让我的访客眼睛更快乐。谢谢你:)

【问题讨论】:

标签: javascript jquery html css animation


【解决方案1】:

哎呀,太早了大约 30 分钟发布。

这是没有 :target 状态操作和完整 URL 更改的滚动解决方案,其他人遇到问题的解决方案:

  <script>
var $root = $('html, body');
$('a').click(function() {
    var href = $.attr(this, 'href');
    $root.animate({
        scrollTop: $(href).offset().top
    }, 500, function () {
        window.location.hash = href;
    });
    return false;
});
    </script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-22
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多