我使用jquery创建一个插件,它使用鼠标滚动事件。 问题是即使我向上滚动它也会向下滚动。
这里我得到了我的代码
HTML:
<body>
<!-- <div id="element"></div> -->
<div id='wrapper'>
<img id='img1' src='./images/image1.jpg'>
</div>
<script>
$(document).ready(function()
{
$(document).scrollPage();
});
</script>
</body>
使用Javascript:
$.extend(Plugin.prototype, {
init: function () {
document.addEventListener('scroll', this.checkScroll);
},
checkScroll: function(event) {
//Guess the delta.
var delta = 0;
if (event.wheelDelta) {
delta = event.wheelDelta/120;
}
else if (event.detail) {
delta = -event.detail/3;
}
if(delta / 120 > 0){
console.log('up');
}
else{
console.log('down');
}
}
});
不知何故,当我滚动代码时,总是会出现在else语句console.log('down');
中是公式delta / 120&gt;这个代码0错了?
答案 0 :(得分:0)
检查当前的scrollTop与之前的scrollTop
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
// downscroll code
} else {
// upscroll code
}
lastScrollTop = st;
});
答案 1 :(得分:0)
我的解决方案:
/**
* Plugin that makes the screen scroll particular component visible on the screen
*/
$.fn.scrollTo = function() {
var isVisibleOnScreen = function(elem) {
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
};
if(!isVisibleOnScreen(this)){
$('html, body').animate({
scrollTop: $(this).offset().top + 'px'
}, 'fast');
return this; // for chaining...
}
};
用法:
$( '#' 顶部)scrollTo();
答案 2 :(得分:0)
$.extend(Plugin.prototype, {
init: function () {
var mousewheelevt=(/Firefox/i.test(navigator.userAgent))? 'DOMMouseScroll' : 'mousewheel';
if (document.attachEvent){
document.attachEvent('on'+mousewheelevt, function(e){scroller(e)});
}
else if (document.addEventListener){
document.addEventListener(mousewheelevt, function(e){scroller(e)},false);
}
function scroller(evt)
{
//Guess the delta.
var delta = 0;
if (!evt) evt = window.event;
if (evt.wheelDelta) {
delta = evt.wheelDelta/120;
}
else if (evt.detail) {
delta = -evt.detail/3;
}
if(delta /120 > 0){
console.log('up');
}
else{
console.log('down');
}
}
}
});