jQuery脚本不使用Rails应用程序

时间:2014-02-13 07:42:22

标签: jquery ruby-on-rails

只是启动了一个小型的Rails应用程序,现在我只有一个静态页面,我试图为链接到该页面上的锚点添加一个平滑的滚动效果。您可以在http://kylerm42.herokuapp.com看到该网站。我注意到脚本被包含在内,所以我知道它没有被遗漏。当我将静态页面与jQuery一起放入JSFiddle时,一切都按预期工作。但它不会对我的本地机器或生产产生影响。这是以下链接:http://jsfiddle.net/YtJcL/478/

在SO的答案中找到了jQuery,以下是代码:

$(".scroll").click(function (event) {
event.preventDefault();
//calculate destination place
var dest = 0;
if ($(this.hash).offset().top > $(document).height() - $(window).height()) {
    dest = $(document).height() - $(window).height();
} else {
    dest = $(this.hash).offset().top;
}
//go to destination
$('html,body').animate({
    scrollTop: dest
}, 1500, 'swing');
});

我的猜测是某些默认的Rails文件存在干扰,但我还没有足够的经验知道在哪里查看。这也可能是我在路上的某个地方犯下的一个简单错误。任何帮助表示赞赏!谢谢!

6 个答案:

答案 0 :(得分:1)

您是否尝试检查脚本是否已连接到应用程序? 将简单日志添加到脚本中,然后检查浏览器控制台。

console.log('Houston we have a problem!');

如果您什么都没看到,那么您的脚本似乎没有在资产文件夹

中的application.js中连接

我检查你的代码,它有效。

如果您有单独的脚本:myscript.js尝试将其添加到application.js

//= require ./where_is_your_script/myscript

//= require myscript

UPD:对于测试,我将你的代码添加到application.js而没有$(document).ready及其工作,但是不要在家里进行

答案 1 :(得分:1)

将您的点击事件包含在:

jQuery(function(){
   //here
});

$(document).ready(function(){
  //here
});

答案 2 :(得分:0)

你没有在页面加载时调用你的滚动函数,你应该在$(document).ready函数中包含这个jquery。

我在您的网站上执行了此功能,并且正在运行。

答案 3 :(得分:0)

我的猜测是在加载类.scroll的元素之前加载脚本。

将您的代码包装在$(document).ready(function() { ..code...});中,以便在dom准备就绪后执行,或者将其从$(".scroll").click(function (event) {更改为$(document).on("click", ".scroll", function(event) { ....

第二个是有效的,因为它拦截了文档上的所有点击事件,并检查目标是否具有类.scroll。因此,如果在脚本执行后页面上出现了额外的.scroll元素,那么它甚至可以工作。

答案 4 :(得分:0)

为什么这么复杂?

$(function() {
    if(window.location.hash && $(window.location.hash).css('display') == 'block'){
        destinator = $(window.location.hash).offset().top;
        $('body, html').animate( { scrollTop: destinator }, 1100 );
    }

    $('.scroll').click(function(){
        if( $(this).attr('data-to') > window.height())
        destinator = $(window.location.hash).offset().top;
        $('body, html').animate( { scrollTop: destinator }, 1500 );
    })
})

第一个条件检查哈希标记,如果是,则滚动到该块。单击时会激活第二个功能,并且" ID"块的属性采用" data-to"。

抱歉我的英语不好

答案 5 :(得分:0)

在开发模式下它能正常工作吗? 如果是,则确认环境/ production.rb包含

  # Disable Rails's static asset server (Apache or nginx will already do this).
  config.serve_static_assets = false

  # Compress JavaScripts and CSS.
  config.assets.js_compressor = :uglifier
  # config.assets.css_compressor = :sass

  # Do not fallback to assets pipeline if a precompiled asset is missed.
  config.assets.compile = true

  # Generate digests for assets URLs.
  config.assets.digest = true