滚动某些距离后弹出文本不起作用

时间:2014-07-12 01:52:53

标签: javascript jquery html css

我正在尝试以不同的y滚动间隔在固定位置弹出文本,但是,我似乎无法正确链接脚本。它似乎跳过显示第一条消息的第一个动作。

代码: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();

2 个答案:

答案 0 :(得分:2)

您的功能应该有不同的名称。尝试

var startY1 = 900;
var stopY1 = 1800;
var startY2 = 1801;
var stopY2 = 2500;

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

function checkY()
{
    console.log($(window).scrollTop()); 
    if($(window).scrollTop() > startY1 && $(window).scrollTop() <= stopY1)
    {
        console.log("Show"); 
        $('.foxedDiv').show(); 
    }
    else
    {
        console.log("Hide"); 
        $('.foxedDiv').hide();
    }

    if($(window).scrollTop() > startY2 && $(window).scrollTop() <= stopY2)
    {
        console.log("Show"); 

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

checkY();

固定小提琴:

http://jsfiddle.net/k8bnd/1/

答案 1 :(得分:1)

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

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 Demo