简体   繁体   English

实现平滑滚动,同时保留:target css动画功能

[英]implementing smooth scrolling while leaving :target css animations functional

i am trying to implement smooth scrolling while leaving css :target animations in tact and functional for anchor links. 我正在尝试实现平滑滚动,同时保持css:target动画完好无损,并具有锚链接的功能。

i believe the problem comes from the :target state being manipulated by the js, and thus overriding the css animations. 我认为问题出在js操纵的:target状态,从而覆盖了CSS动画。 in order to draw attention to the headline of a selected # section, i change the padding slightly on :target, like so: 为了吸引人们注意所选#部分的标题,我在:target上略微更改了填充,如下所示:

html 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 的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;
}

it works as an animation exactly as i would like, except that the anchor link of course causes a page jump instead of smooth scrolling action. 它完全按照我的意愿作为动画工作,除了锚链接当然会导致页面跳转而不是平滑的滚动动作。 and the problem comes when adding: 问题出现在添加时:

js 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;
        }
    }
});

in an attempt to make that page transition smoother. 试图使页面过渡更加平滑。 i have tried using other jQuery plugins for manipulating page location, but sadly to no avail (and i do not have js // jQuery experience). 我曾尝试使用其他jQuery插件来操纵页面位置,但可惜没有用(而且我没有js // jQuery经验)。 any help or tips would be cherished by me and make my visitors eyes happier. 我会珍惜任何帮助或技巧,并使我的访客更加快乐。 thank you :) 谢谢 :)

oops, posted about 30 min too early. 糟糕,发布时间过早约30分钟。

here's the scrolling solution without :target state manipulation and full URL change, solution should anyone else run into the problem: 这是没有: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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM