我正在使用 Ariel Flesler 的带有 bootstrap 的 rollTo 插件。它看起来非常简单,但我无法让它发挥作用。我想单击按钮,它会平滑地滚动到相应的 id。这是一个按钮的示例。
这是 html:
<a class="btn btn-primary" href="#faqs"></i>FAQS</a>
<div class="id="faqs">
<script src="js/jquery.scrollTo-1.4.3.1-min.js"></script>
Qn。 1 jQuery 应该是什么样的,以便我的所有按钮都能工作?
Qn。 2 顺便说一句,我从 twitter bootstrap 的网站“application.js”窃取了它们,但没有理解它们的含义,只是为了让我的网站正常工作。你能解释一下这些代码的含义吗?
//Is this bit of code the convention to add to the start of every jQuery doc?
!function ($) {
$(function(){
var $window = $(window)
//What does this do?
$('[href^=#]').click(function (e) {
e.preventDefault()
})
//This code scrolls smoothly to top, however it only works when the code below is present. Why?
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
})
// This is the weird bit of code I don't understand. Without this, my scrollTop doesn't work. Could this bit of code also interfere with scrollTo's plugin? I assume it will...
$('.download-btn .btn').on('click', function () {
var css = $("#components.download input:checked")
.map(function () { return this.value })
.toArray()
, js = $("#plugins.download input:checked")
.map(function () { return this.value })
.toArray()
, vars = {}
, img = ['glyphicons-halflings.png', 'glyphicons-halflings-white.png']
感谢您回答我的所有问题,非常感谢。
最佳答案
看这个:
//Is this bit of code the convention to add to the start of every jQuery doc?
!function ($) {
$(function(){ //<--------------this is where jQuery starts working 'document ready function'
var $window = $(window)
还有这个:
//What does this do?
$('[href^=#]').click(function (e) {
e.preventDefault();
});
上面的脚本.preventDefault()
确保任何 <a>
属性为 href="#"
的标签点击页面时不会跳到顶部,这与 return false;
相同
和下面的代码:
//This code scrolls smoothly to top, however it only works
//when the code below is present. Why?
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
是的,这会起作用,因为它选择了 <a>
具有 href='#top'
的标签此处的属性,当单击此属性时,html, body
会滚动到文档顶部0
位置。然而,这仅适用于此链接 $("a[href='#top']")
正如您没有提到完整的代码,但如果您想滚动到特定的 div,这不会造成任何损害。您可以修改 $("a[href='#top']").click(function() {
或$('[href^=#]').click(function (e) {
代码使所有链接正常工作。
您可以尝试这个脚本:
$('[href^=#]').click(function (e) {
e.preventDefault();
var div = $(this).attr('href');
$("html, body").animate({
scrollTop: $(div).position().top
}, "slow");
});
在此处的 fiddle 中结账:http://jsfiddle.net/Ja6DN/
关于jQuery 滚动插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14332512/