简体   繁体   中英

How can I make my numbered scale responsive to scrolling and clicking?

So I'm creating an interactive piece using a numbered scale (Bortle Scale for dark skies if that helps at all). I want the scale to remain on the page for most of the piece while the user scrolls through different explanations of each number on the scale. The scale is just a vertical line of numbers, each in their own circle with no fill and a 1px solid border.

Here's what I want it to do: say you're scrolling from the explanation for level 2 to the explanation for level 3. When you're on 2, that circle has a color fill. When you scroll past 2 to 3, then 3 gets the color fill and 2 returns to no fill. This happens in both directions. I'd also like for users to be able to click on each circle and be taken to the corresponding page. So you click on 2 and you are whooshed to the explanation section for 2.

I honestly have no idea how to do this, only have the HTML and CSS written out. Here's the HTML:

<div class="bortlescale">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
    <div>7</div>
    <div>8</div>
    <div>9</div>
</div>  

And here's the CSS:

.bortlescale div {
    border:1px solid white;
    margin: 60px;
    margin-right:0px;
    padding:5px;
    width:60px;
    text-align: center;
    border-radius: 100px;
    position: relative;
    color:white;
    font-family:"Museo300Regular";
}

I really hope someone can help me with this! Thanks!

You need to get the scrollTop value of $(window) while scrolling, then compare it to each 'explanation' offset().top position to determine where the user has scrolled to.

var $scales = $('.bortlescale div'),
    $explanations = $('.explanation div'),
    winH = $(window).height(),
    topSpacing = 50;//you can set this one

$explanations.height(winH);

/* scrolling */
$(window).scroll(function(){
    var st = $(this).scrollTop();

    $explanations.each(function(index){
         var offset = $(this).offset(),
             h = $(this).height();

        if(st >= offset.top - topSpacing && st < offset.top + h - topSpacing){
            $scales.eq(index).css({'background':'red'});//color fill it
        }else{
            $scales.eq(index).css({'background':'none'});//remove color fill
        }
    });
})

/* clicking */
$scales.click(function(){
    var index = $(this).index(),
        $target = $explanations.eq(index),
        pos = $target.offset().top;

    $('body').stop().animate({scrollTop:pos-topSpacing},'slow');

});

See this jsfiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM