我已经输入了几个带有字母d的行中带有ID的几个div,例如:#d1,#d2,#d3 ...然后我在下面创建了javascript代码:
var pos = 0;
$("#button-up").on('click', function(e) {
e.preventDefault();
if(pos > 1){
pos -= 1;
$("html, body").stop().animate({
'scrollTop': $("#d"+pos).offset().top-300},200,"swing");
};
});
$("#button-down").on('click', function(e) {
e.preventDefault();
if(pos < 10){
pos += 1;
$("html, body").stop().animate({
'scrollTop': $("#d"+pos).offset().top-300},200,"swing");
};
});
window.addEventListener("scroll", function(event) {
var posi = this.pageYOffset;
if(posi-(pos-1)*1070+50 >= 1070){pos += 1} else if((pos-1)*1070+50-posi <= -1070){pos -= 1};
});
最后,当我点击按钮时我的网站向下滚动,但我需要点击两次按钮向上滚动。为什么?有没有比这更好的方法来获得预期的结果呢?
答案 0 :(得分:0)
我让它改变了这一部分:
window.addEventListener("scroll", function(event) {
var posi = this.pageYOffset;
if(posi-(pos-1)*1070+50 >= 1070){pos += 1} else if((pos-1)*1070+50-posi <= -1070){pos -= 1};
});
这一个:
window.addEventListener("mousewheel", function(e) {
e.preventDefault();
console.log('passou por 6');
var evt = window.event || e //equalize event object
evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible
var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
if(delta > 0) {
if(pos > 1){
console.log('passou por 3');
pos -= 1;
$("html, body").stop().animate({
'scrollTop': $("#d"+pos).offset().top-300},200,"swing");
};
//scroll up
console.log('cima');
}
else{
if(pos < 10){
pos += 1;
$("html, body").stop().animate({
'scrollTop': $("#d"+pos).offset().top-300},200,"swing");
};
console.log('baixo');
//scroll down
};
});
答案 1 :(得分:0)
使用jquery scoll功能
$(window).scroll(function(event){
// your code
});