简体   繁体   English

如何使用rails和javascript查找并返回我的div元素?

[英]How can I find and return my div element with rails and javascript?

I am trying to build a piece of javascript that take the url from the web page looks to see if there was an anchor included in the address then it will scroll down the page to the anchor, I have to do this because bootstraps sticky-top nav blocks the view of the element I am trying to view. 我正在尝试构建一段Javascript,该JavaScript从网页上获取该URL,以查看地址中是否包含锚点,然后它将页面向下滚动到该锚点,我必须这样做,因为bootstraps sticky-top导航会阻止我尝试查看的元素的视图。

My js looks like 我的js看起来像

findLink = function(){
  link = document.location.href
  parseLink(link)
}

parseLink = function(link) {
  if (link.split('').includes('#')) {
    post_id = link.split('#')[1];
    moveLink(post_id)
  }
}

moveLink = function(post_id){
  element = $('#+post_id').get()

}

$(document).on('turbolinks:load', findLink()) ||
$(document).on('page:load', findLink())

my issue is that even if I try to find 我的问题是,即使我尝试寻找

console.log($('#my_id')) # returns jQuery.fn.init {}
console.log($('#my_id').get()) # returns an empty []

I get two empty arrays. 我得到两个空数组。 I am not sure why this is happening or how to fix it. 我不确定为什么会这样或如何解决。

I ended up writing some JS its not perfect but it gets the job done. 我最终写了一些不完美的JS,但它完成了工作。

document.addEventListener('turbolinks:load', function(){
  link = document.location.href
  parseLink(link)
});

parseLink = function(link) {
  if (link.split('').includes('#')) {
    post_id = link.split('#')[1];
    moveLink(post_id)
  }
}

moveLink = function(post_id){
  element = document.getElementById(post_id)
  $('html,body').animate({
    scrollTop: $(element).position().top -= 200
   });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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