我有一个链接<a href="#test">link to test</a>
,当点击它时,该页面会立即跳转到“测试”内容。
如何在此页内链接之间切换时如何添加转换?
非常感谢你:D
编辑: 如果我可以使用css关键帧而不是jquery动画,那将是很好的。 有人解决方案吗?
答案 0 :(得分:2)
我假设你的意思是顺利滚动到目标而不是突然跳到那里。如果是这样,这是一种使用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>
答案 1 :(得分:2)
最快的方法是在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
答案 2 :(得分:1)
这是一个jquery示例:
$(document).on('click', 'a', function(event){
event.preventDefault();
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
});
和小提琴:http://jsfiddle.net/9SDLw/。 代码和小提琴都不是我的,这是我在这里找到的答案Smooth scrolling when clicking an anchor link
答案 3 :(得分:1)
使用CSS动画关键帧是不可能的,滚动位置不是可以受影响的CSS属性。您可以使用Javascript或许多javascript库(例如:jQuery)更改页面滚动的位置。