首页 \ 问答 \ 根据y的位置设置导航活动(setting nav active based on position of y)

根据y的位置设置导航活动(setting nav active based on position of y)

因此,不是描述我想要完成的任务,而是在屏幕的右侧,他们有一个导航,根据您所使用的幻灯片,将更改“活动”导航项。

所以如果我使用position()函数和子类.top,我想到了这一点。 (正如你将在我的代码中看到的,如果我说<position.top它可以正常工作)除了它绝对不会让我使用任何条件语句让我比较AGAINST position.top(你将在我的代码中看到我的当我尝试执行var> position.top时,第二个条件语句不会运行。

希望有人可以就如何做到这一点给我一些建议,如果是这样或其他什么的话。

$.fn.followTo = function ( pos ) {
    var $this = this,
        $window = $(windw);

    $window.scroll(function(e){
        if ($this.hasClass("green"))
    {
          if ($window.scrollTop() < pos) {
        $this.css({
            background: 'green'
        });
        } else {
        $this.css({

            background: 'black'
        });
        }
    }


    });
};
var a = $(".slide1n");
var Aposition = a.position();

if(Aposition.top < 875)
{
  //this runs
  $('.slide1n').addClass('green');
  $('.slide1n').followTo(875);
}

if(Aposition.top > 875)
{
  //this doesnt run
  $('.slide1n').removeClass('green');
  $('.slide2n').addClass('green');
  $('.slide2n').followTo(1550);
}

我还尝试了其他一些我找到的东西,但仍然没有工作(在我发布这个问题之前,我回到谷歌并进行了另一次搜索并发现了一种不同的方式,它仍然无法正常工作)这对我来说没有任何意义如果前两个语句(我尝试不同的时间)工作正常,如果它小于该数量,并且使用我的followTo函数,当div超出界限时div会从绿色变为黑色,所以如果超出界限则div超出界限因为它变黑了必须高于875。 我没有资源。 提前致谢。

var a = parseInt($(".slide1n").css("top"));

if (a > 0 && a < 875) {
  //this runs
}

if (a > 876) {
  $('body').hide(); //doesnt run this 
}

/ **编辑***** /

HTML(已请求)

  <div class="slide1n"></div>
  <div class="slide2n"></div>
  <div class="slide3n"></div>
  <div class="slide4n"></div>
  <div class="slide5n"></div>

现场演示


So instead of describing what I am trying to accomplish, here is an example On the right side of the screen they have a nav and based on what slide you are on will change the 'active' nav item.

So I have this figured out if I use the position() function and subclass .top. (as you will see in my code, it works fine if I say < position.top) except it absolutely just won't let me use any conditional statement that lets me compare AGAINST position.top (as you will see in my code my second conditional statement doesn't run when I try to do var > position.top).

Was hoping someone can lend me some advice on how I can do this, if it's this way or something else.

$.fn.followTo = function ( pos ) {
    var $this = this,
        $window = $(windw);

    $window.scroll(function(e){
        if ($this.hasClass("green"))
    {
          if ($window.scrollTop() < pos) {
        $this.css({
            background: 'green'
        });
        } else {
        $this.css({

            background: 'black'
        });
        }
    }


    });
};
var a = $(".slide1n");
var Aposition = a.position();

if(Aposition.top < 875)
{
  //this runs
  $('.slide1n').addClass('green');
  $('.slide1n').followTo(875);
}

if(Aposition.top > 875)
{
  //this doesnt run
  $('.slide1n').removeClass('green');
  $('.slide2n').addClass('green');
  $('.slide2n').followTo(1550);
}

I also tried something else I found, that is STILL not working (before I posted this question, I went back to google and did another search and found a different way, and it's still not working) This just is not making sense to me since if the first two statements (both different times I tried it) work fine if it's less than that amount, and with my followTo function, the div changes from green to black when it's out of bounds, so if it's out of bounds that div's top MUST be above 875 since it turned black. I am out of resources. Thanks in advance.

var a = parseInt($(".slide1n").css("top"));

if (a > 0 && a < 875) {
  //this runs
}

if (a > 876) {
  $('body').hide(); //doesnt run this 
}

/** EDITS *****/

HTML (was requested)

  <div class="slide1n"></div>
  <div class="slide2n"></div>
  <div class="slide3n"></div>
  <div class="slide4n"></div>
  <div class="slide5n"></div>

LIVE DEMO


原文:https://stackoverflow.com/questions/24666394
更新时间:2020-03-26 12:18

最满意答案

我对你的问题采取了一些自由,并决定采用我的常规JS解决方案来实现scrollspy。

($(function(){
    // create a cache of used elements
    var $els = [];
    $els.nav = $('#nav');
    $els.header = $('#header');
    $els.window = $(window);
    $els.indicators = $('.indicators');

    var lastId,
    headerHeight = $els.header.outerHeight(),
    // All list items
    menuItems = $els.nav.find('a'),
    // Anchors corresponding to menu items
    scrollItems = menuItems.map(function(){
        var item = $($(this).attr('href'));
        if (item.length) { return item; }
    });

    // fancy scroll over time to anchor
    function scrollTo(e) {
        e.preventDefault();
        var target = $(this).attr('href');
        var topDistance = $(target).offset().top + headerHeight;
        menuItems.parent().find('.active').removeClass('active');
        $(this).parent().addClass('active');
        // need to trigger this on both as browsers differ from one another
        $('body, html').animate({scrollTop: topDistance + 'px'}, 200);
    }

    function checkAnchorUpdate(){
        // Return a list of elements above of at where we are scrolled to
        var cur = scrollItems.map(function(){
            if ($(this).offset().top <= $els.window.scrollTop() - headerHeight){
                return this;
            }
        });

        // Get the last element in the returned list
        cur = cur[cur.length-1];
        // get element's id attribute, default to 'slide1'
        var id = cur && cur.length ? cur[0].id : "slide1";
        // stops us triggering the active states again and again
        if (lastId !== id) {
            lastId = id;
            // Set/remove active class
            $els.indicators.removeClass('active');
            $('#'+id+'n').addClass('active');
            menuItems
            .parent().removeClass("active")
            .end().filter("[href=\"#"+id+"\"]").parent().addClass("active");

        }  
    }

    $els.window.on('scroll', checkAnchorUpdate);
    menuItems.on('click', scrollTo);
}));

您可能需要做一些警告和改进,例如:

  • 当你到达页面底部时触发最后一个项目的“活动”状态(在较大的屏幕上,有时你不能向右滚动到底部元素,但这只是个人偏好)。
  • 出于性能原因,在窗口上的'scroll'触发器(例如Ben Alman的Throttle / Bebounce jQuery插件)中添加一个油门/去抖动器
  • 目前,如果您希望为特定幻灯片显示指标,则必须为每个要显示的“指标”设置一个顶级菜单项

DEMO FIDDLE


I took some liberties with your question and decided to go down my normal go-to JS solution for scrollspy.

($(function(){
    // create a cache of used elements
    var $els = [];
    $els.nav = $('#nav');
    $els.header = $('#header');
    $els.window = $(window);
    $els.indicators = $('.indicators');

    var lastId,
    headerHeight = $els.header.outerHeight(),
    // All list items
    menuItems = $els.nav.find('a'),
    // Anchors corresponding to menu items
    scrollItems = menuItems.map(function(){
        var item = $($(this).attr('href'));
        if (item.length) { return item; }
    });

    // fancy scroll over time to anchor
    function scrollTo(e) {
        e.preventDefault();
        var target = $(this).attr('href');
        var topDistance = $(target).offset().top + headerHeight;
        menuItems.parent().find('.active').removeClass('active');
        $(this).parent().addClass('active');
        // need to trigger this on both as browsers differ from one another
        $('body, html').animate({scrollTop: topDistance + 'px'}, 200);
    }

    function checkAnchorUpdate(){
        // Return a list of elements above of at where we are scrolled to
        var cur = scrollItems.map(function(){
            if ($(this).offset().top <= $els.window.scrollTop() - headerHeight){
                return this;
            }
        });

        // Get the last element in the returned list
        cur = cur[cur.length-1];
        // get element's id attribute, default to 'slide1'
        var id = cur && cur.length ? cur[0].id : "slide1";
        // stops us triggering the active states again and again
        if (lastId !== id) {
            lastId = id;
            // Set/remove active class
            $els.indicators.removeClass('active');
            $('#'+id+'n').addClass('active');
            menuItems
            .parent().removeClass("active")
            .end().filter("[href=\"#"+id+"\"]").parent().addClass("active");

        }  
    }

    $els.window.on('scroll', checkAnchorUpdate);
    menuItems.on('click', scrollTo);
}));

There are some caveats and improvements you might want to make such as:

  • When you reach the bottom of the page trigger the 'active' state on the last item (on larger screens sometimes you wont be able to scroll right to the bottom element, but this is just a personal preference).
  • Add a throttle/debouncer to the 'scroll' trigger on window (such as Ben Alman's Throttle/Bebounce jQuery plugin) for performance reasons
  • Currently you have to have a top menu item for each of the 'indicators' you want to be visible if you want the indicator to show for a particular slide

DEMO FIDDLE

2014-07-10

相关文章

更多

最新问答

更多
  • css在元素之前中断列而不破坏包装器(css break column before element without breaking the wrapper)
  • 如何在Xamarin共享项目中使用自定义渲染器(How to use Custom Renderer in Xamarin Shared Project)
  • 如何为特定表中的特定字段设置唯一?(How to set unique for specific field from specific table?)
  • Google SDK iOS - sign()方法完成处理程序(Google SDK iOS - sign() method completion handler)
  • 在具有接口{}值的地图上实现String()(Implement String() on a map with interface{} values)
  • 检查数据库中是否已存在用户名(Check if username already exist in DB)
  • 使用javascript进行ajax调用时阻止用户交互(Block user interaction while doing ajax call using javascript)
  • 什么'if(err)'在Javascript中精确测试?(What does 'if (err)' tests precisely in Javascript?)
  • jQuery mouseleave无法正常工作(jQuery mouseleave not working)
  • 寻求使用的一些说明(Seeking some clarification on use of )
  • 将数组传递给注释的语法(syntax for passing array to annotation)
  • 用于从两个日期范围之间的文件中提取数据的Shell脚本(Shell script to extract data from file between two date ranges)
  • 元素隐藏但父()没有(Element hides but parent() not)
  • 如何使用Google App Engine Java平台开发web ui(How to develop web ui with Google App Engine Java platform)
  • 对于OWL A级;(For an OWL class A; Getting all properties that A is their domain)
  • Excel VBA公式格式问题(Excel VBA Formula Format Issue)
  • ORA - 02287序列号不允许在这里(ORA - 02287 sequence number not allowed here)
  • Github拉忽略特定文件(Github Pull Ignore Specific File)
  • SQL CONVERT函数在SQL Server中工作但不在应用程序中(SQL CONVERT function working in SQL Server but not in application)
  • backbone.js适用于大型应用程序(backbone.js for large applications)
  • 防止程序关闭(Preventing program from closing)
  • 生成不带图像的heightMap(Generating a heightMap without an Image)
  • Bootstrap - 如何将包含文本的div居中?(Bootstrap - How to center div that has text inside it?)
  • Android - 片段findViewById()总是null?(Android - Fragment findViewById() always null?)
  • 确定CSS中的高度(Figuring out heights in CSS)
  • 使用__autoload包含类和使用命名空间(Use __autoload to include class and use namespace)
  • setTimeout()不允许我传递文本值[重复](setTimeout() doesn't allow me to pass text values [duplicate])
  • 在NSUserDefault中恢复值(Restoring value in NSUserDefault)
  • 知道如何将这种下沉的悬停效果添加到图像/链接吗?(Any idea how to add this sinking hover effect to an image/link?)
  • 在XIB中淡入/淡出UISegmentedControl(fade in/fade out UISegmentedControl in XIB)