2017-04-05 34 views
0

这jQuery代码使我的页面上的箭头滚动页面。我觉得有一个更好更短的方法来做到这一点。我可以将所有这些代码合并到一个函数中,还是这是唯一的方法吗?

//Functions that make the arrows on the page scroll through the page. 
$("#arrow1").click(function() { 
    $('html, body').animate({ 
     scrollTop: $("#aboutMe").offset().top 
    }, 1000); 
}); 

$("#arrow2").click(function() { 
    $('html, body').animate({ 
     scrollTop: $("#skillsPart").offset().top 
    }, 1000); 
}); 

$("#arrow3").click(function() { 
    $('html, body').animate({ 
     scrollTop: $("#contactMe").offset().top 
    }, 1000); 
}); 

$("#arrow4").click(function() { 
    $('html, body').animate({ 
     scrollTop: $("#topPart").offset().top 
    }, 1000); 
}); 
+0

根据您的实际标记可以减少它只是一个功能,请包括 – DaniP

+0

烨。当然可以编写干净的代码。 –

+0

你必须使用这些确切的ID吗?我有一个6行解决方案,但我改变了'.offset()'元素的id名称。 –

回答

-2

我有一个答案可能不是你所寻找的,但仍然是我猜...

$("#arrow1,#arrow2,#arrow3,#arrow4").click(function() { 
 
    var a1 = $("#aboutMe").offset().top, 
 
    a2 = $("#skillsPart").offset().top, 
 
    a3 = $("#contactMe").offset().top, 
 
    a4 = $("#topPart").offset().top; 
 
    switch ($(this).attr("id") { 
 
    case "arrow1": 
 
     $('html, body').animate({ 
 
     scrollTop: a1 
 
     }, 1000); 
 
     break; 
 
    case "arrow2": 
 
     $('html, body').animate({ 
 
     scrollTop: a2 
 
     }, 1000); 
 
     break; 
 
    case "arrow3": 
 
     $('html, body').animate({ 
 
     scrollTop: a3 
 
     }, 1000); 
 
     break; 
 
    case "arrow4": 
 
     $('html, body').animate({ 
 
     scrollTop: a4 
 
     }, 1000); 
 
     break; 
 
    } 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

https://jsfiddle.net/mn6184p1/2/

+1

哈。没有评论或空白,它仍然比原来更多的线条。提示:'$('html,body')。animate {{'不需要在事件处理程序中多次。 –

+0

@KevinB是的,不是最好的方法: - | –

+0

https:// jsfiddle.net/mn6184p1/3/,如果内容没有改变,你可以将地图移动到处理程序之外,并且可以在为元素提供所有相同的'arrow'类名后,用.arrow替换该复杂的选择器。 –

0

你可以创建一个可重用的函数,通过添加要滚动的元素和元素,您可以轻松添加更多的点击处理程序l至入els阵列

var main = $('html, body'); 
function handleClick(el, scrollToEl) { 
    el.click(function() { 
    main.animate({ 
     scrollTop: scollToEl.offset().top 
    }, 1000); 
    }) 
} 

var els = [ 
    [$('#arrow1'), $("#aboutMe")], 
    [$('#arrow2'), $("#skillsPart")], 
    [$('#arrow3'), $("#contactMe"], 
    [$('#arrow4'), $("#topPart")] 
]; 

els.forEach(function(el){ 
    handleClick(el[0], el[1]); 
}); 
相关问题