[英]css keyframe animation on clicking an anchor ('#') link
我有一个链接<a href="#test">link to test</a>
,当单击它时,页面将立即跳转到“测试”内容。 在此页内链接之间切换时如何添加过渡? 非常感谢你:D
编辑:如果我可以使用css关键帧而不是jquery动画,那就太好了。 有人解决吗?
我假设您是要平滑滚动到目标,而不是突然跳到那里。 如果是这样,这是使用javascript和jQuery的一种方法。
$(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 }, 1000); return false; } } }); });
div { min-height: 200vh; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#test">test</a> <div></div> <div id="test">test</div>
最快的方法是在jQuery中加载并插入此代码段。
步骤1:在结束body
标签( </body>
)之前插入jQuery脚本标签
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
步骤2:在下方插入此代码段
<script>
// Bind all a href clicks to this function
$(document).on('click', 'a', function(event){
// Prevent default events
event.preventDefault();
// Animate the body (html page) to scroll to the referring element
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 1000);
});
</script>
您可以编辑显示1000
以更改速度,还可以添加或减去scrollTop: $( $.attr(this, 'href') ).offset().top
以获取元素的其他偏移量。
示例:这将是元素上方100像素,而不是完全位于顶部。
scrollTop: $( $.attr(this, 'href') ).offset().top - 100
这是一个jQuery示例:
$(document).on('click', 'a', function(event){
event.preventDefault();
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
});
和一个小提琴: http : //jsfiddle.net/9SDLw/ 。 代码和小提琴都不是我的,这是我在这里找到的答案单击锚点链接时平滑滚动
使用CSS动画关键帧无法做到这一点,滚动位置不是会受到影响的CSS属性。 您可以使用Javascript或许多JavaScript库(例如jQuery)更改页面滚动的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.