如何在鼠标滚轮上使用jquery调用一次函数?

时间:2015-12-27 15:35:40

标签: javascript jquery scroll

我有一个部分,一旦进入,身体的溢出被设置为隐藏,用户必须滚动以触发某些动画才能进入下一部分。我使用var delta = e.originalEvent.wheelDelta;捕获任何滚动尝试。我的问题是,当我使用.on('mousewheel')时,当我只想要一个函数时,我会返回一些函数调用。我怎样才能做到这一点?谢谢。这是我正在使用的代码:

$('html').on ('mousewheel', function (e) {
    var delta = e.originalEvent.wheelDelta;
    if($('body').hasClass('fp-viewing-secondPage')) {
        if(delta < 0 ){
            var something = (function() {
                var executed = false;
                return function () {
                    if (!executed) {
                        executed = true;
                        console.log('call me once please');
                    }
                };
            });
            something();
         }

     });
}

这是我尝试过的其他事情:

if($body.hasClass('fp-viewing-secondPage')) {
                    if($body.hasClass('setAn1')){
                        $('html').one('mousewheel', function (e) {
                            var delta = e.originalEvent.wheelDelta;
                            console.log('animation 1');
                            $body.addClass('setAn2').removeClass('setAn1');
                        });
                    } if($body.hasClass('setAn2')){
                        $('body').one('mousewheel', function (e) {
                            var delta = e.originalEvent.wheelDelta;
                            console.log('animation 2');
                            $body.addClass('setAn3');
                        });
                    } if($body.hasClass('setAn3')){
                        $('html').one('mousewheel', function (e) {
                            var delta = e.originalEvent.wheelDelta;
                            console.log('animation 3');
                            alert('moving on to next section');
                        });
                    }
                }

但是这段代码只运行第一个setAn1?是因为.one?

3 个答案:

答案 0 :(得分:2)

选中此JS Fiddle,而不是on('mousewheel)我仅使用on('scroll'进行演示。

因此secret设置为false,一旦我们输入div#test部分,我们就会在这种情况下运行函数 - console.log(),然后设置{{ 1}}到secret,因此该函数只会被调用一次。

然后,当我们离开该部分时,将true设置回secret,以便我们可以再次运行所需的功能,如果我们再次输入false部分,但功能仍然是每次只发射一次。

&#13;
&#13;
#test
&#13;
var secret = false,
    testTop = $('#test').offset().top,
    testHeight = $('#test').height(),
    scrlTop;

$(window).on('scroll', function(){
	scrlTop = $(this).scrollTop();
  if(scrlTop > testTop && scrlTop < testTop+testHeight){
  	if(!secret){
    	console.log('call me once please');
      secret = true;
    }  	
  }else{
  	secret = false;  	
  }
});
&#13;
body{ margin:0; padding:0; height:1500px; background-color:orange; }
#test{ margin-top:700px; height:400px; width:100%; background-color:#090; }
&#13;
&#13;
&#13;

以上代码每次进入<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div id="test"></div>部分时都会触发一次功能,但是如果您的目标是仅运行一次该功能,那么无论是否他离开那部分,只需删除这部分:JS Fiddle 2

#test

----------

更新1:

将此JS Fiddle 3 -updated 2与以下代码结合使用: - 已更新 -

&#13;
&#13;
else{
    secret = false;
} 
&#13;
var secret = [false, false, false, false, false],
    sections = $('.sections'),
    secHeight = $('#one').height(),
    body = $('html, body'), //select both html and body cross-browser fix
    links = $('#links a'),
    prevLinkId = 0,
    linkId, secHeight, scrlTop, diff;
    
links.each(function(index){
    $(this).on('click', function(e){
        e.preventDefault();
        secHeight = $('#one').height();
        linkId = $(this).attr('id');
        linkId = linkId.replace('lnk', '');
        links.removeClass('highlight');
        $(links[linkId]).addClass('highlight');
        diff = Math.abs(linkId - prevLinkId);
        timeDelay = diff * 250;
        distance = index * secHeight;
        body.animate({scrollTop: distance} , timeDelay);
        prevLinkId = linkId;
    });
});
    
$(window).on('scroll', function(){
    scrlTop = $(this).scrollTop();
    playOnce();
});

$(window).on('DOMMouseScroll mousewheel', function(e){
    scrlTop = $(this).scrollTop();
    if(e.originalEvent.detail > 0 || e.originalEvent.wheelDelta < 0) {
        //scroll down
        body.animate({scrollTop: scrlTop + 50} , 20);
    }else {
        //scroll up
        body.animate({scrollTop: scrlTop - 50} , 20);
    }
    playOnce();
});

function playOnce(){
    secHeight = $('#one').height();
    if(scrlTop >= 0 && scrlTop < secHeight){
        if(secret[0] == false){
            console.log('this is Section One');
            secret = [true, false, false, false, false];
        }
    }else if(scrlTop >= secHeight && scrlTop < 2 * secHeight){
        if(secret[1] == false){
            console.log('this is Section Two');
            secret = [false, true, false, false, false];
        }
    }
    else if(scrlTop >= 2 * secHeight && scrlTop < 3 * secHeight){
        if(secret[2] == false){
            console.log('this is Section Three');
            secret = [false, false, true, false, false];
        }
    }
    else if(scrlTop >= 3 * secHeight && scrlTop < 4 * secHeight){
        if(secret[3] == false){
            console.log('this is Section Four');
            secret = [false, false, false, true, false];
        }
    }else if(scrlTop >= 4 * secHeight && scrlTop < 5 * secHeight){
        if(secret[4] == false){
            console.log('this is Section Five');
            secret = [false, false, false, false, true];
        }
    }
}
&#13;
body{
  margin:0;
  padding:0;
  height:1500px;
  overflow:hidden;
}
#links{
  width:65px;
  height:30px;
  line-height:30px;
  background-color:rgba(0,0,0, 0.7);
  margin-top:5px;
  margin-left:-10px;
  border-top-right-radius:15px;
  border-bottom-right-radius:15px;
  color:white;
  padding-left:20px;
  box-shadow: 2px 2px 5px rgba(0,0,0,0.6);
  position:fixed;
  z-index:1000;
  overflow:hidden;
  transition:all 0.5s ease-in-out;
  cursor:default;
}
#links:hover{
  width:190px;
  transition:all 0.5s ease-in-out;
}
#links a{
  width:22px;
  line-height:22px;
  display:inline-block;
  border-radius:50%;
  text-decoration:none;
  color:#444;
  background-color:rgba(255,255,255, 0.7);
  text-align:center;
  font-weight:bold;
  transition:all 0.3s ease-in-out;
}
#links a:hover, #links .highlight{
  background-color:black;
  color:#EEE;
}
.sections{
  width:100%;
  height:100vh;
  color:white;
  text-align:center;
  font-size:72px;
  line-height:100vh;
  text-shadow:0 0 5px rgba(0,0,0,0.7);
}
#one{background-color:green}
#two{background-color:orange}
#three{background-color:tomato}
#four{background-color:skyblue}
#five{background-color:navy}
&#13;
&#13;
&#13;

<强> TL; DR
使用5个<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div id="links"> Section <a id="lnk0" href="#one" class="highlight">1</a> <a id="lnk1" href="#two">2</a> <a id="lnk2" href="#three">3</a> <a id="lnk3" href="#four">4</a> <a id="lnk4" href="#five">5</a> </div> <div id="one" class="sections">Section ONE</div> <div id="two" class="sections">Section TWO</div> <div id="three" class="sections">Section THREE</div> <div id="four" class="sections">Section FOUR</div> <div id="five" class="sections">Section Five</div> div模拟整页部分,以及一系列切换 - 或标记 - .sections,因为secret = [false, false, false, false, false]不会使页面滚动,我们我需要使用以下代码监听body{overflow:hidden}事件并检测滚动方向:

mouseweel

现在在// Listening to DOMMouseScroll and mousewheel events together will make // this code work correctly cross-browser. // same thing for e.originalEvent.detail and e.originalEvent.wheelDelta $(window).on('DOMMouseScroll mousewheel', function(e){ scrlTop = $(this).scrollTop(); if(e.originalEvent.detail > 0 || e.originalEvent.wheelDelta < 0) { //scrolling down body.animate({scrollTop: scrlTop + 50} , 20); }else { //scrolling up body.animate({scrollTop: scrlTop - 50} , 20); } // calling playOnce function playOnce(); }); 函数中,我们有5个级别的if语句,每个级别检查playOnce()值以查看窗口是否在相应的scrollTop() div上,即:

.section

----------

更新2:

如果您不想调用该功能 - 重复动画 - 当用户离开某个部分然后滚动回来时,请查看此JS fiddle 4 ,您需要在javascript中进行的唯一更改是,在某个部分,而不是将else if(scrlTop >= 3 * secHeight && scrlTop < 4 * secHeight){ if(secret[3] == false){ // 3 because arrays starts from zero console.log('this is Section Four'); // we set the 4th element in the secret array to true and the rest to // false, thus we ensure that we don't fire the function more than once // as long as the user has not left the 4th element upward or down secret = [false, false, false, true, false]; } 数组中的相应元素设置为secret并将所有其他元素设置为true,我们设置关于DOM排名的/之前的部分,所以对于第3节,false数组将是:

secret

而不是:

secret = [true, true, true, false, false];

在上一个解决方案中,每次离开后都可以调用该函数。

答案 1 :(得分:1)

如果您只想调用一次事件处理程序,则可以使用jQuery&#39; .one()函数:

$('html').one ('mousewheel', function (e) {
    // gets called once here..
});

jQuery一个函数:http://api.jquery.com/one/

答案 2 :(得分:0)

您可能正在寻找一种名为Throttling的编程模式,其中一个函数每X秒只能调用一次。

在具体情况下,您的代码无效,因为您在闭包内实例化library(lazyeval) # so we can use interpret library(dplyr) var1 <- "cyl" var2 <- "mpg" mtcars %>% group_by_(var1) %>% #note the _ summarize_(Sum = interp(~sum(x), x = as.name(var2))) %>% #note the _ and the interp call arrange(desc(Sum)) Source: local data frame [3 x 2] cyl Sum (dbl) (dbl) 1 4 293.3 2 8 211.4 3 6 138.2 (每次执行var executed时都是A.K.A)。您需要将变量保存到全局范围内(使用something()代替window.executed只是一种简单但难看的方式)