JavaScript上下滚动不可预测
JavaScript scrolling unpredictable up and down
我遇到了一个大问题或小问题。我正在尝试滚动我的网站,所以每个容器都会滑动到网站顶部的特定位置。但是,就我所见,这是一个问题,因为如果你点击第一个项目,然后点击下一个项目,脚本会滚动到相同的位置,但如果你点击上一个项目上方的项目,它会滚动到页面底部。
我的脚本是一个简单的锚脚本,看看:
$("a.scrollForMe").each(function() { // go through all links
var href = $(this).attr("href");
if (typeof(href) == "undefined") { return; }
if ($(this).attr("href").match(/^#/)) { // if href starts with #
$(this).click(function() { // add a click event to it
var name = $(this).attr("href").substring(1); // get the anchor link
// on click, scroll to the a with a name attribute matching the anchor
$('html, body').animate({scrollTop: $("section[name='" + name + "']").offset().top - 420}, 1000);
//alert ("This height is: " + $("section[name='" + name + "']").height() + " and it's name is " + name);
});
}
});
如果你想看看目前的工作情况,请查看我的网站:http://1st-issue.de/2012/redaxo/#sec10
我希望你能帮助我!提前感谢!
如果使用此代码可能会更好。我在保存页面上进行了测试。
$(document).ready(function() {
$("a.scrollForMe").each(function() { // go through all links
var href = $(this).attr("href");
if (typeof(href) == "undefined") { return; }
if (href.match(/^#/)) { // if href starts with #
$(this).click(function() { // add a click event to it
var name = href.substring(1); // get the anchor link
// on click, scroll to the a with a name attribute matching the anchor
$('html, body').animate({scrollTop: $("section[name='" + name + "']").prevAll("section").first().offset().top + 100 }, 1000);
//alert ("This height is: " + $("section[name='" + name + "']").height() + " and it's name is " + name);
});
}
});
});
如果我能给你一个建议,你不应该使用href来锚定,因为屏幕会自动跳转到锚定。使用您添加的代码,屏幕会闪烁,因为浏览器会转到相应的锚点,然后执行scrollTop动画。但这只是一个建议。
相关文章:
- JavaScript上下滚动不可预测
- $('body').height()变化不可预测
- MVC 在不可预测的时间从 razor @Helper 调用 Javascript
- 为什么纳肖恩的乐观打字会产生不可预测的结果
- 为什么 .offset() 位置是不可预测的
- javascript,forEach 和 removeChild 不可预测的行为
- 数组排序不正确/不可预测,使用 indexOf 时
- 禁用预测滚动 - 鼠标滚轮 (OnScroll) 事件触发过于频繁(触摸板)
- jquery's的就绪功能是不可预测的
- 组合然后排序Javascript数组.得到不可预测的结果
- 为什么Javascript异常会使解释器处于不可预测的状态
- AngularJS-使用angular.forEach和console.log循环遍历数组是不可预测的
- JavaScript 'for in' 语句给出不可预测的结果
- Google Chrome'的不可预测的行为在alert()函数
- JS/ JQuery keyup和keydown在Android设备上的不可预测行为
- ElasticSearch和不可预测的搜索文档
- 在JavaScript中按值从数组中删除项,结果不可预测
- 一段Javascript代码导致浏览器不可预测的崩溃
- gulp中不可预测的文件顺序
- 从本地文件到 Web 服务器进行 ajax 调用时不可预测的 JavaScript 执行顺序