javascript - 移动到[取消]隐藏元素

标签 javascript jquery

我有一些 jQuery,我正在尝试以特定的方式工作。我想隐藏和取消隐藏一个元素,并在其显示后将焦点放在暴露的区域上。有一个链接#welcomeselect,单击该链接后应显示隐藏元素#welcome。如果我单击包含以下代码的链接,它将仅取消隐藏该元素;如果我再次单击它,它只会移动到显示的元素。我在另一个网站上找到的自定义显示代码(scrollToAnchor);我只需要能够移动到取消隐藏元素,平滑过渡不是必需的。我究竟做错了什么。

$('#welcomeselect').click(function(){
    $('#welcome').show();
scrollToAnchor("#welcome");
});

 // scroll handler http://bradsknutson.com/blog/smooth-scrolling-to-anchor-with-jquery/

 var scrollToAnchor = function( id ) {
     // grab the element to scroll to based on the name
     var elem = $("a[name='"+ id +"']");
     // if that didn't work, look for an element with our ID
     if ( typeof( elem.offset() ) === "undefined" ) {
         elem = $("#"+id);
     }
     // if the destination element exists
     if ( typeof( elem.offset() ) !== "undefined" ) {
         // do the scroll
         $('html, body').animate({
             scrollTop: elem.offset().top
         }, 1000 );
     }
     };

     // bind to click event - http://bradsknutson.com/blog/smooth-scrolling-to-anchor-with-jquery/

     $("a").click(function( event ) {            
         // only do this if it's an anchor link
         if ( $(this).attr("href").match("#") ) {                
            // cancel default event propagation
            event.preventDefault();              
            // scroll to the location
            var href = $(this).attr('href').replace('#', '')
            scrollToAnchor( href );              
         }           
    });     

最佳答案

已更新

这个元素在显示元素时移动(id 中只有一个额外的哈希值):

$('#welcomeselect').click(function(){
  $('#welcome').show();
  scrollToAnchor("welcome");
});


上一页

给你,这个只有在元素显示后才会移动:

$('#welcomeselect').click(function(){
  $('#welcome').show(function(){
    scrollToAnchor("welcome");
  });
});

var scrollToAnchor = function( id ) {
  // grab the element to scroll to based on the name
  var elem = $("a[name='"+ id +"']");
  // if that didn't work, look for an element with our ID
  if ( typeof( elem.offset() ) === "undefined" ) {
    elem = $("#"+id);
  }

  // if the destination element exists
  if ( typeof( elem.offset() ) !== "undefined" ) {
    // do the scroll

    $('html, body').animate({
      scrollTop: elem.offset().top
    }, 1000 );

  }
};

关于javascript - 移动到[取消]隐藏元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23667703/

相关文章:

javascript - 当父函数接收不同参数时如何实现管道

c# - ASP.NET MVC3 向下钻取复选框列表

javascript - jQuery Mobile - 动态可折叠在一定数量后停止添加

javascript - 去掉@后面的单词

javascript - 创建 jquery 函数,如果空白则将焦点重定向到输入,否则执行正常搜索

javascript - 完整日历中同一日期的多个事件问题

javascript - 添加新事件时在 jQuery weekcalendar 中获取 userId

Jquery获取已按下输入的文本框的ID?

javascript - jquery-ui 可排序占位符位置错误

javascript - CSS 或 Javascript : How to fit two portrait images side by side in a container with fluid width?