滚动一定距离后弹出文本不工作 [英] Pop up text after scrolling certain distances is not working

查看:102
本文介绍了滚动一定距离后弹出文本不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让文字弹出在固定的位置,在不同的y滚动间隔,但是,我似乎不能链接脚本正确。似乎会跳过显示第一封邮件的第一个动作。

I'm trying to get text to pop up at a fixed location at different y-scroll intervals however, I can't seem to chain the scripts correctly. It seems to skip the first action of displaying the first message.

代码: http://jsfiddle.net/k8bnd/

var startY = 1500;
var stopY = 2000;

$(window).scroll(function(){
checkY();
});

function checkY()
{
console.log($(window).scrollTop()); 
if($(window).scrollTop() > startY && $(window).scrollTop() <= stopY)
{
    console.log("Show"); 

    $('.titleTwo').show(); 
}
else
{
    console.log("Hide"); 
    $('.titleTwo').hide();
} }
checkY();


推荐答案

这是因为你覆盖了以前的值/功能。为了使这个更加动态,你可以添加data- *属性到每个消息元素,指定它们有效的位置。然后在滚动事件中检查每个元素的位置数据,如果窗口在该范围内,则显示它,否则隐藏它。

This is happening because you have overwritten the previous values/functions. To make this more dynamic you can add data-* attributes to each message element specifying which positions they are valid for. And then in the scroll event check each element's position data, if the window is within that range show it, otherwise hide it.

HTML

<!-- Changed the classes both elements had to foxedDiv
     so that we can select them as a group and loop over them -->
<div class="foxedDiv" data-position="900,1800">
    MESSAGE 1
</div>    
<div class="foxedDiv" data-position="1801,2500">
    MESSAGE 2
</div>

JS

//Note you do not need to make an anonymous
//function just to do the call for checkY
//just pass the function
$(window).scroll(checkY);

function checkY(){
    //save this value so we dont have to call the function everytime
    var top = $(window).scrollTop();
    console.log(top); 
    $(".foxedDiv").each(function(){
       var positionData = $(this).data("position").split(",");
       if(top > positionData[0] && top <= positionData[1]){
           console.log("Show"); 
           $(this).show(); 
       } else {
           console.log("Hide"); 
           $(this).hide();
       }       
    });
}
checkY();

JSFiddle演示

这篇关于滚动一定距离后弹出文本不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆