【问题标题】:Javascript does not work from a bootstrap template in railsJavascript 不适用于 rails 中的引导模板
【发布时间】:2017-01-31 19:21:15
【问题描述】:

我创建了一个新的 rails 应用程序并安装了所有必要的 gem。添加了所有文件。更新了 application.js 文件。一切正常,但由于某种原因,所有与 javascript 相关的东西都不起作用。我正在使用这个模板:

https://startbootstrap.com/template-overviews/creative/

我也使用部分导航栏。 我错过了什么?如果您需要更多信息,请告诉我!

app/assets/javascripts/application.js

// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery-ui
//= require magnific-popup
//= require welcomes
//= require jquery.easing
//= require scrollReveal
//= require jquery_ujs
//= require turbolinks
//= require_tree .

宝石文件

source 'https://rubygems.org'

gem 'jquery-ui-rails'
gem 'scrollreveal-rails'
gem 'magnific-popup-rails', '~> 1.1.0'
gem 'jquery-easing-rails'

gem "font-awesome-rails"
gem 'bootstrap-sass'

gem 'rails', '4.2.0'
gem 'sqlite3'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc

group :development, :test do
  gem 'byebug'
  gem 'web-console', '~> 2.0'
  gem 'spring'
end

app/assets/javascripts/welcomes.js

(function($) {
    "use strict"; // Start of use strict

    // jQuery for page scrolling feature - requires jQuery Easing plugin
    $('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: ($($anchor.attr('href')).offset().top - 50)
        }, 1250, 'easeInOutExpo');
        event.preventDefault();
    });

    // Highlight the top nav as scrolling occurs
    $('body').scrollspy({
        target: '.navbar-fixed-top',
        offset: 51
    });

    // Closes the Responsive Menu on Menu Item Click
    $('.navbar-collapse ul li a').click(function() {
        $('.navbar-toggle:visible').click();
    });

    // Offset for Main Navigation
    $('#mainNav').affix({
        offset: {
            top: 100
        }
    })

    // Initialize and Configure Scroll Reveal Animation
    window.sr = ScrollReveal();
    sr.reveal('.sr-icons', {
        duration: 600,
        scale: 0.3,
        distance: '0px'
    }, 200);
    sr.reveal('.sr-button', {
        duration: 1000,
        delay: 200
    });
    sr.reveal('.sr-contact', {
        duration: 600,
        scale: 0.3,
        distance: '0px'
    }, 300);

    // Initialize and Configure Magnific Popup Lightbox Plugin
    $('.popup-gallery').magnificPopup({
        delegate: 'a',
        type: 'image',
        tLoading: 'Loading image #%curr%...',
        mainClass: 'mfp-img-mobile',
        gallery: {
            enabled: true,
            navigateByImgClick: true,
            preload: [0, 1] // Will preload 0 - before current, and 1 after the current image
        },
        image: {
            tError: '<a href="%url%">The image #%curr%</a> could not be loaded.'
        }
    });

})(jQuery); // End of use strict

_header.html.erb

<nav id="mainNav" class="navbar navbar-default navbar-fixed-top">
  <div class="container-fluid">

    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        <span class="sr-only">Toggle navigation</span> Menu <i class="fa fa-bars"></i>
      </button>
      <a class="navbar-brand page-scroll" href="#page-top">Start Bootstrap</a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav navbar-right">
        <li>
            <a class="page-scroll" href="#about">About</a>
        </li>
        <li>
            <a class="page-scroll" href="#services">Services</a>
        </li>
        <li>
            <a class="page-scroll" href="#portfolio">Portfolio</a>
        </li>
        <li>
            <a class="page-scroll" href="#contact">Contact</a>
        </li>
      </ul>
    </div>
    <!-- /.navbar-collapse -->

  </div>
  <!-- /.container-fluid -->
</nav>

<header>
  <div class="header-content">

    <div class="header-content-inner">
      <h1 id="homeHeading">Your Favorite Source of Free Bootstrap Themes</h1>
      <hr>
      <p>Start Bootstrap can help you build better websites using the Bootstrap CSS framework! Just download your template and start going, no strings attached!</p>
      <a href="#about" class="btn btn-primary btn-xl page-scroll">Find Out More</a>
    </div>

  </div>
</header>

index.html.erb

<section class="bg-primary" id="about">
  <div class="container">
    <div class="row">
        <div class="col-lg-8 col-lg-offset-2 text-center">
          <h2 class="section-heading">We've got what you need!</h2>
          <hr class="light">
          <p class="text-faded">Start Bootstrap has everything you need to get your new website up and running in no time! All of the templates and themes on Start Bootstrap are open source, free to download, and easy to use. No strings attached!</p>
          <a href="#services" class="page-scroll btn btn-default btn-xl sr-button">Get Started!</a>
        </div>
    </div>
  </div>
</section>

<section id="services">

  <div class="container">
    <div class="row">
      <div class="col-lg-12 text-center">
        <h2 class="section-heading">At Your Service</h2>
        <hr class="primary">
      </div>
    </div>
  </div>

  <div class="container">
    <div class="row">

      <div class="col-lg-3 col-md-6 text-center">
        <div class="service-box">
          <i class="fa fa-4x fa-diamond text-primary sr-icons"></i>
          <h3>Sturdy Templates</h3>
          <p class="text-muted">Our templates are updated regularly so they don't break.</p>
        </div>
      </div>
      <div class="col-lg-3 col-md-6 text-center">
        <div class="service-box">
          <i class="fa fa-4x fa-paper-plane text-primary sr-icons"></i>
          <h3>Ready to Ship</h3>
          <p class="text-muted">You can use this theme as is, or you can make changes!</p>
        </div>
      </div>
      <div class="col-lg-3 col-md-6 text-center">
        <div class="service-box">
          <i class="fa fa-4x fa-newspaper-o text-primary sr-icons"></i>
          <h3>Up to Date</h3>
          <p class="text-muted">We update dependencies to keep things fresh.</p>
        </div>
      </div>
      <div class="col-lg-3 col-md-6 text-center">
        <div class="service-box">
          <i class="fa fa-4x fa-heart text-primary sr-icons"></i>
          <h3>Made with Love</h3>
          <p class="text-muted">You have to make your websites with love these days!</p>
        </div>
      </div>

    </div>
  </div>

</section>

<section class="no-padding" id="portfolio">
  <div class="container-fluid">
    <div class="row no-gutter popup-gallery">

      <div class="col-lg-4 col-sm-6">
        <a href="img/portfolio/fullsize/1.jpg" class="portfolio-box">
          <%= image_tag("1.jpg", alt: "#", :class => "img-responsive") %>
          <div class="portfolio-box-caption">
            <div class="portfolio-box-caption-content">
              <div class="project-category text-faded">
                Category
              </div>
              <div class="project-name">
                Project Name
              </div>
            </div>
          </div>
        </a>
      </div>

      <div class="col-lg-4 col-sm-6">
        <a href="img/portfolio/fullsize/2.jpg" class="portfolio-box">
          <%= image_tag("2.jpg", alt: "#", :class => "img-responsive") %>
          <div class="portfolio-box-caption">
            <div class="portfolio-box-caption-content">
              <div class="project-category text-faded">
                Category
              </div>
              <div class="project-name">
                Project Name
              </div>
            </div>
          </div>
        </a>
      </div>

      <div class="col-lg-4 col-sm-6">
        <a href="img/portfolio/fullsize/3.jpg" class="portfolio-box">
          <%= image_tag("3.jpg", alt: "#", :class => "img-responsive") %>
          <div class="portfolio-box-caption">
            <div class="portfolio-box-caption-content">
              <div class="project-category text-faded">
                Category
              </div>
              <div class="project-name">
                Project Name
              </div>
            </div>
          </div>
        </a>
      </div>

      <div class="col-lg-4 col-sm-6">
        <a href="img/portfolio/fullsize/4.jpg" class="portfolio-box">
          <%= image_tag("4.jpg", alt: "#", :class => "img-responsive") %>
          <div class="portfolio-box-caption">
            <div class="portfolio-box-caption-content">
              <div class="project-category text-faded">
                Category
              </div>
              <div class="project-name">
                Project Name
              </div>
            </div>
          </div>
        </a>
      </div>

      <div class="col-lg-4 col-sm-6">
        <a href="img/portfolio/fullsize/5.jpg" class="portfolio-box">
          <%= image_tag("5.jpg", alt: "#", :class => "img-responsive") %>
          <div class="portfolio-box-caption">
            <div class="portfolio-box-caption-content">
              <div class="project-category text-faded">
                Category
              </div>
              <div class="project-name">
                Project Name
              </div>
            </div>
          </div>
        </a>
      </div>

      <div class="col-lg-4 col-sm-6">
        <a href="img/portfolio/fullsize/6.jpg" class="portfolio-box">
          <%= image_tag("6.jpg", alt: "#", :class => "img-responsive") %>
          <div class="portfolio-box-caption">
            <div class="portfolio-box-caption-content">
              <div class="project-category text-faded">
                Category
              </div>
              <div class="project-name">
                Project Name
              </div>
            </div>
          </div>
        </a>
      </div>

    </div>
  </div>
</section>

<aside class="bg-dark">
  <div class="container text-center">
    <div class="call-to-action">
      <h2>Free Download at Start Bootstrap!</h2>
      <a href="http://startbootstrap.com/template-overviews/creative/" class="btn btn-default btn-xl sr-button">Download Now!</a>
    </div>
  </div>
</aside>

<section id="contact">
  <div class="container">
    <div class="row">
      <div class="col-lg-8 col-lg-offset-2 text-center">
        <h2 class="section-heading">Let's Get In Touch!</h2>
        <hr class="primary">
        <p>Ready to start your next project with us? That's great! Give us a call or send us an email and we will get back to you as soon as possible!</p>
      </div>
      <div class="col-lg-4 col-lg-offset-2 text-center">
        <i class="fa fa-phone fa-3x sr-contact"></i>
        <p>123-456-6789</p>
      </div>
      <div class="col-lg-4 text-center">
        <i class="fa fa-envelope-o fa-3x sr-contact"></i>
        <p><a href="mailto:your-email@your-domain.com">feedback@startbootstrap.com</a></p>
      </div>
    </div>
  </div>
</section>

application.html.erb

<!DOCTYPE html>
<html>
<head>
  <title>Template</title>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  <%= csrf_meta_tags %>

  <%= render 'layouts/shim' %>
</head>
<body>

<%= render 'layouts/header' %>
<%= yield %>
<%= render 'layouts/footer' %>

</body>
</html>

application.css.scss

@import "bootstrap-sprockets";
@import "bootstrap";
@import "jquery-ui/all";
@import "font-awesome";
@import "magnific-popup";

html,
body {
  height: 100%;
  width: 100%;
}

body {
  font-family: 'Merriweather', 'Helvetica Neue', Arial, sans-serif;
}

hr {
  border-color: #F05F40;
  border-width: 3px;
  max-width: 50px;
}

hr.light {
  border-color: white;
}

a {
  -webkit-transition: all 0.35s;
  -moz-transition: all 0.35s;
  transition: all 0.35s;
  color: #F05F40;
}

a:hover,
a:focus {
  color: #eb3812;
}

h1,
h2,
h3,
h4,
h5,
h6 {
  font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif;
}

p {
  font-size: 16px;
  line-height: 1.5;
  margin-bottom: 20px;
}

.bg-primary {
  background-color: #F05F40;
}

.bg-dark {
  background-color: #222222;
  color: white;
}

.text-faded {
  color: rgba(255, 255, 255, 0.7);
}

section {
  padding: 100px 0;
}

aside {
  padding: 50px 0;
}

.no-padding {
  padding: 0;
}

.navbar-default {
  background-color: white;
  border-color: rgba(34, 34, 34, 0.05);
  font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif;
  -webkit-transition: all 0.35s;
  -moz-transition: all 0.35s;
  transition: all 0.35s;
}

.navbar-default .navbar-header .navbar-brand {
  color: #F05F40;
  font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif;
  font-weight: 700;
  text-transform: uppercase;
}

.navbar-default .navbar-header .navbar-brand:hover,
.navbar-default .navbar-header .navbar-brand:focus {
  color: #eb3812;
}

.navbar-default .navbar-header .navbar-toggle {
  font-weight: 700;
  font-size: 12px;
  color: #222222;
  text-transform: uppercase;
}

.navbar-default .nav > li > a,
.navbar-default .nav > li > a:focus {
  text-transform: uppercase;
  font-weight: 700;
  font-size: 13px;
  color: #222222;
}

.navbar-default .nav > li > a:hover,
.navbar-default .nav > li > a:focus:hover {
  color: #F05F40;
}

.navbar-default .nav > li.active > a,
.navbar-default .nav > li.active > a:focus {
  color: #F05F40 !important;
  background-color: transparent;
}

.navbar-default .nav > li.active > a:hover,
.navbar-default .nav > li.active > a:focus:hover {
  background-color: transparent;
}

@media (min-width: 768px) {

  .navbar-default {
    background-color: transparent;
    border-color: rgba(255, 255, 255, 0.3);
  }

  .navbar-default .navbar-header .navbar-brand {
    color: rgba(255, 255, 255, 0.7);
  }

  .navbar-default .navbar-header .navbar-brand:hover,
  .navbar-default .navbar-header .navbar-brand:focus {
    color: white;
  }

  .navbar-default .nav > li > a,
  .navbar-default .nav > li > a:focus {
    color: rgba(255, 255, 255, 0.7);
  }

  .navbar-default .nav > li > a:hover,
  .navbar-default .nav > li > a:focus:hover {
    color: white;
  }

  .navbar-default.affix {
    background-color: white;
    border-color: rgba(34, 34, 34, 0.05);
  }

  .navbar-default.affix .navbar-header .navbar-brand {
    color: #F05F40;
    font-size: 14px;
  }

  .navbar-default.affix .navbar-header .navbar-brand:hover,
  .navbar-default.affix .navbar-header .navbar-brand:focus {
    color: #eb3812;
  }

  .navbar-default.affix .nav > li > a,
  .navbar-default.affix .nav > li > a:focus {
    color: #222222;
  }

  .navbar-default.affix .nav > li > a:hover,
  .navbar-default.affix .nav > li > a:focus:hover {
    color: #F05F40;
  }

}

header {
  position: relative;
  width: 100%;
  min-height: auto;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  -o-background-size: cover;
  background-position: center;
  background-image: asset-data-url("header.jpg");
  text-align: center;
  color: white;
}

header .header-content {
  position: relative;
  text-align: center;
  padding: 100px 15px 100px;
  width: 100%;
}

header .header-content .header-content-inner h1 {
  font-weight: 700;
  text-transform: uppercase;
  margin-top: 0;
  margin-bottom: 0;
  font-size: 30px;
}

header .header-content .header-content-inner hr {
  margin: 30px auto;
}

header .header-content .header-content-inner p {
  font-weight: 300;
  color: rgba(255, 255, 255, 0.7);
  font-size: 16px;
  margin-bottom: 50px;
}

@media (min-width: 768px) {

  header {
    min-height: 100%;
  }

  header .header-content {
    position: absolute;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
    padding: 0 50px;
  }

  header .header-content .header-content-inner {
    max-width: 1000px;
    margin-left: auto;
    margin-right: auto;
  }

  header .header-content .header-content-inner h1 {
    font-size: 50px;
  }

  header .header-content .header-content-inner p {
    font-size: 18px;
    max-width: 80%;
    margin-left: auto;
    margin-right: auto;
  }

}

.section-heading {
  margin-top: 0;
}

.service-box {
  max-width: 400px;
  margin: 50px auto 0;
}

@media (min-width: 992px) {

  .service-box {
    margin: 20px auto 0;
  }

}

.service-box p {
  margin-bottom: 0;
}

.portfolio-box {
  position: relative;
  display: block;
  max-width: 650px;
  margin: 0 auto;
}

.portfolio-box .portfolio-box-caption {
  color: white;
  opacity: 0;
  display: block;
  background: rgba(240, 95, 64, 0.9);
  position: absolute;
  bottom: 0;
  text-align: center;
  width: 100%;
  height: 100%;
  -webkit-transition: all 0.35s;
  -moz-transition: all 0.35s;
  transition: all 0.35s;
}

.portfolio-box .portfolio-box-caption .portfolio-box-caption-content {
  width: 100%;
  text-align: center;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

.portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-category,
.portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-name {
  font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif;
  padding: 0 15px;
}

.portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-category {
  text-transform: uppercase;
  font-weight: 600;
  font-size: 14px;
}

.portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-name {
  font-size: 18px;
}

.portfolio-box:hover .portfolio-box-caption {
  opacity: 1;
}

.portfolio-box:focus {
  outline: none;
}

@media (min-width: 768px) {

  .portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-category {
    font-size: 16px;
  }

  .portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-name {
    font-size: 22px;
  }

}

.call-to-action h2 {
  margin: 0 auto 20px;
}

.text-primary {
  color: #F05F40;
}

.no-gutter > [class*='col-'] {
  padding-right: 0;
  padding-left: 0;
}

.btn-default {
  color: #222222;
  background-color: white;
  border-color: white;
  -webkit-transition: all 0.35s;
  -moz-transition: all 0.35s;
  transition: all 0.35s;
}

.btn-default:hover,
.btn-default:focus,
.btn-default.focus,
.btn-default:active,
.btn-default.active,
.open > .dropdown-toggle.btn-default {
  color: #222222;
  background-color: #f2f2f2;
  border-color: #ededed;
}

.btn-default:active,
.btn-default.active,
.open > .dropdown-toggle.btn-default {
  background-image: none;
}

.btn-default.disabled,
.btn-default[disabled],
fieldset[disabled] .btn-default,
.btn-default.disabled:hover,
.btn-default[disabled]:hover,
fieldset[disabled] .btn-default:hover,
.btn-default.disabled:focus,
.btn-default[disabled]:focus,
fieldset[disabled] .btn-default:focus,
.btn-default.disabled.focus,
.btn-default[disabled].focus,
fieldset[disabled] .btn-default.focus,
.btn-default.disabled:active,
.btn-default[disabled]:active,
fieldset[disabled] .btn-default:active,
.btn-default.disabled.active,
.btn-default[disabled].active,
fieldset[disabled] .btn-default.active {
  background-color: white;
  border-color: white;
}

.btn-default .badge {
  color: white;
  background-color: #222222;
}

.btn-primary {
  color: white;
  background-color: #F05F40;
  border-color: #F05F40;
  -webkit-transition: all 0.35s;
  -moz-transition: all 0.35s;
  transition: all 0.35s;
}

.btn-primary:hover,
.btn-primary:focus,
.btn-primary.focus,
.btn-primary:active,
.btn-primary.active,
.open > .dropdown-toggle.btn-primary {
  color: white;
  background-color: #ee4b28;
  border-color: #ed431f;
}

.btn-primary:active,
.btn-primary.active,
.open > .dropdown-toggle.btn-primary {
  background-image: none;
}

.btn-primary.disabled,
.btn-primary[disabled],
fieldset[disabled] .btn-primary,
.btn-primary.disabled:hover,
.btn-primary[disabled]:hover,
fieldset[disabled] .btn-primary:hover,
.btn-primary.disabled:focus,
.btn-primary[disabled]:focus,
fieldset[disabled] .btn-primary:focus,
.btn-primary.disabled.focus,
.btn-primary[disabled].focus,
fieldset[disabled] .btn-primary.focus,
.btn-primary.disabled:active,
.btn-primary[disabled]:active,
fieldset[disabled] .btn-primary:active,
.btn-primary.disabled.active,
.btn-primary[disabled].active,
fieldset[disabled] .btn-primary.active {
  background-color: #F05F40;
  border-color: #F05F40;
}

.btn-primary .badge {
  color: #F05F40;
  background-color: white;
}

.btn {
  font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif;
  border: none;
  border-radius: 300px;
  font-weight: 700;
  text-transform: uppercase;
}

.btn-xl {
  padding: 15px 30px;
}

::-moz-selection {
  color: white;
  text-shadow: none;
  background: #222222;
}

::selection {
  color: white;
  text-shadow: none;
  background: #222222;
}

img::selection {
  color: white;
  background: transparent;
}

img::-moz-selection {
  color: white;
  background: transparent;
}

body {
  webkit-tap-highlight-color: #222222;
}

【问题讨论】:

  • 可能只是印刷错误。您的意思是 /app/assets/javascripts(带有“s”),对吗?
  • @DmitryKukhlevsky 是的,我打印错了! ;)
  • 在浏览器中使用开发者模式时,您是否看到 html 页面中包含 javascript? (或查看页面源代码时)
  • @DmitryKukhlevsky 不,当我在 chrome 中使用开发人员工具并查看控制台时它是空的
  • 那么请发布您的布局文件。它可能缺少 javascript_include_tag 'application'

标签: javascript jquery ruby-on-rails twitter-bootstrap


【解决方案1】:

我终于成功了!首先,我从新开始,我创建了一个新的 rails 应用程序,因为我处于绝望模式并安装到许多 Gems 并更改了代码,最后代码是一团糟。

这一次我采取了不同的方法,我没有使用任何额外的 gem,我手动安装了所有必要的插件,这意味着只需将所有文件复制并粘贴到正确的目录中并将它们链接在一起。 我不得不删除javascript目录中的coffeescript文件,因为该文件引起了一些问题。如您所见,我还必须在正文标记内手动放置一个触发器,否则 ScrollSpy 函数将不起作用(data-spy="scroll" data-target=".navbar-fixed-top")。出于某种原因,Javascript 仍然无法正常工作,但我已经读到 Javascript/jQuery 如果未正确加载,则可能会导致一些问题。所以我删除了 //= require_tree 。在 javascript 文件中。并按正确的顺序放置每个 javascript。我可以通过查看工作模板的源代码来找出正确的顺序。但它仍然没有工作!然后我将 " true %>" 放在标签的最后,这样 javascript 就会最后加载。 ...终于成功了!我的下一步是删除 application.js 文件中的 turbolinks 行,我会更改:

<%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %> 

进入

<%= stylesheet_link_tag    'application', media: 'all' %>

因为我已经读到 turbolinks 可能会导致使用 javascript 的资产管道出现一些问题。

application.html.erb

<!DOCTYPE html>
<html lang="en">
  <head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Creativetemplate</title>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
    <%= csrf_meta_tags %>

  </head>

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

  <body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top">

  <%= render 'layouts/header' %>
  <%= yield %>
  <%= render 'layouts/footer' %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  </body>
</html>

application.js

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap
//= require jquery.easing
//= require scrollreveal
//= require jquery.magnific-popup
//= require welcomes

welcomes.js

(function($) {
    "use strict"; // Start of use strict
    // debugger
    // jQuery for page scrolling feature - requires jQuery Easing plugin
    $('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: ($($anchor.attr('href')).offset().top - 50)
        }, 1250, 'easeInOutExpo');
        event.preventDefault();
    });

    // Highlight the top nav as scrolling occurs
    $('body').scrollspy({
        target: '.navbar-fixed-top',
        offset: 51
    });

    // Closes the Responsive Menu on Menu Item Click
    $('.navbar-collapse ul li a').click(function() {
        $('.navbar-toggle:visible').click();
    });

    // Offset for Main Navigation
    $('#mainNav').affix({
        offset: {
            top: 100
        }
    })

    // Initialize and Configure Scroll Reveal Animation
    window.sr = ScrollReveal();
    sr.reveal('.sr-icons', {
        duration: 600,
        scale: 0.3,
        distance: '0px'
    }, 200);
    sr.reveal('.sr-button', {
        duration: 1000,
        delay: 200
    });
    sr.reveal('.sr-contact', {
        duration: 600,
        scale: 0.3,
        distance: '0px'
    }, 300);

    // Initialize and Configure Magnific Popup Lightbox Plugin
    $('.popup-gallery').magnificPopup({
        delegate: 'a',
        type: 'image',
        tLoading: 'Loading image #%curr%...',
        mainClass: 'mfp-img-mobile',
        gallery: {
            enabled: true,
            navigateByImgClick: true,
            preload: [0, 1] // Will preload 0 - before current, and 1 after the current image
        },
        image: {
            tError: '<a href="%url%">The image #%curr%</a> could not be loaded.'
        }
    });

})(jQuery); // End of use strict

application.css.scss

/*
*= require magnific-popup
*= require welcomes
*/

@import "bootstrap";
@import "font-awesome";

html,
body {
  height: 100%;
  width: 100%;
}

...
...
...

如果有人对 Javascript 和 Asset Pipeline 有类似的问题,我会尝试解决它:

1)确保所有文件都在正确的目录中

2)检查application.css.scss、application.js和application.html.erb中的所有文件是否正确链接在一起

3) 删除“//= require_tree”。行在 application.js 中,因为它加载没有特定顺序的 javascript,并且可能会产生一些问题。以主题的正确顺序手动键入每一行。您可以通过在浏览器中查看模板的源代码来检查正确的顺序。

4) 运行localserver时通过对比源代码检查是否安装了正确的插件版本号,并检查网站与模板网站。

5)如果您不需要javascript目录中的coffeescript文件,请将其删除。

6) 将“javascript_include_tag”从 head 标记内移动到结束 body 标记的正上方。所以javascript可以最后加载。

7) 去掉 application.js 和 application.html.erb 中的 turbolinks。

8) 如果仍然无法正常工作,请检查网站 Chrome 中的开发者工具(控制台),您也可以使用 javascript 文件中的调试器查看是否有任何错误。

希望它对某人有所帮助。

【讨论】:

  • 实际上第5点解决了我的问题。我的app/assets/javascript 文件夹自动生成了一个user.coffee 文件,该文件是空的,正在加载而不是user.js 文件。非常感谢。
【解决方案2】:

我正在编辑我的答案,因为我仍然遇到资产管道问题。

我添加了以下可能有助于找到解决方案的资源,一旦我解决了问题,我将发布解决方案。

https://launchschool.com/blog/rails-asset-pipeline-best-practices

https://railsapps.github.io/rails-javascript-include-external.html

https://reinteractive.com/posts/116-12-tips-for-the-rails-asset-pipeline

我阅读了通过搜索rails资产管道可以找到的所有指南,但我不会将它们全部链接

我的建议是使用 Chrome 开发人员工具检查 application.css 和 application.js 的指纹(通过进入任何屏幕元素,使用 f12 打开开发人员工具箱并检查任何 div 或任何 js 文件的任何样式)。您需要检查文件的指纹版本,然后使用文本编辑器打开该版本并检查文件指纹版本中加载的内容。

如果您的文件(例如 user.js)加载到清单的底部,您应该很容易在指纹应用程序的底部找到它。

如果你想更新这个文件,你可以运行

rake assets:precompile

这将仅在开发中预编译资产,对于生产,您需要指定环境。它将通过您所做的编辑更改指纹文件 application.css 和 application.js。

您也可以通过以下地址localhost:3000/assets/yourjsfile.js查看文件或关注localhost:3000/assets/application-yourfingerprint.js查看指纹版本

如您所见,public/assets 文件夹中包含许多文件,您可以使用rake assets:clean-rf public/assets 删除它们,然后运行rake assets:precompile,它将再次预编译资产。

如果没有包含任何内容,则说明您的 application.js 没有被加载。当我阅读不同的帖子时,您可以尝试以下方法:

  1. 将文件包含在config/initializers/assets.rb 中,代码如下:

    Rails.application.config.assets.precompile += %w( user.js )
    
  2. 启动rails c 并运行Rails.application.config.assets.paths 此命令将以红色显示自动包含的路径,例如 App、Lib 和 Vendor 中的路径,以绿色显示您通过在 config/application.rb 中添加以下代码以添加新路径所包含的路径

    config.assets.paths << Rails.root.join("vendor","assets", "fonts")
    

我过去犯的另一个错误是没有使用正确的 sprockets 语法,您可以在以下链接中检查它(我使用的是 require_user 而不是 require user):

https://github.com/rails/sprockets#sprockets-directives

我的问题是我在 App/assets/javascript 下有两个名为 user 的文件(user.coffee 和 user.js)。第一个被加载的是 user.coffee,它是空的。 感谢trickydiddy

的回答,我找到了解决方案

【讨论】:

  • 谢谢,这对我有帮助! javascript 在您的网站上运行吗?我认为自 Rails 4 以来您不需要 application.html.erb 文件中的
  • 是的,我刚刚测试过。我有 Rails 5,我降级为 'sprockets-rails' '2.3.3'。
  • @trickydiddy 问题是当我运行我的服务器时,我的终端日志中的每个 css、js 和 img 都有一个 get 请求,所以现在我将更新 sprockets 并仔细阅读资产管道让它正常工作。 guides.rubyonrails.org/asset_pipeline.html
  • @trickydiddy 嗨,我编辑了我的帖子,你可以查看它,也许你可以检查localhost:3000/assets/application.js 并发布结果。此讨论可以帮助您找到解决方案stackoverflow.com/questions/16168166/…
  • 谢谢你,我终于成功了,我发布了一个答案,如果你好奇,你可以看看;)
【解决方案3】:

棘手的部分是welcomes.js 和turbolinks。 将您的welcomes.js 转换为咖啡(例如js2coffee),然后将其复制到home.coffee 之类的文件中app/assets/javascripts在第一行添加$(document).on "turbolinks:load", -&gt;

$(document).on "turbolinks:load", ->
  (($) ->
    'use strict'
    # Start of use strict
    # jQuery for page scrolling feature - requires jQuery Easing plugin
    $('a.page-scroll').bind 'click', (event) ->
      $anchor = $(this)
      $('html, body').stop().animate { scrollTop: $($anchor.attr('href')).offset().top - 50 }, 1250, 'easeInOutExpo'
      event.preventDefault()
      return
    # Highlight the top nav as scrolling occurs
    $('body').scrollspy
      target: '.navbar-fixed-top'
      offset: 51
    # Closes the Responsive Menu on Menu Item Click
    $('.navbar-collapse ul li a').click ->
      $('.navbar-toggle:visible').click()
      return
    # Offset for Main Navigation
    $('#mainNav').affix offset: top: 100
    # Initialize and Configure Scroll Reveal Animation
    window.sr = ScrollReveal()
    sr.reveal '.sr-icons', {
      duration: 600
      scale: 0.3
      distance: '0px'
    }, 200
    sr.reveal '.sr-button',
      duration: 1000
      delay: 200
    sr.reveal '.sr-contact', {
      duration: 600
      scale: 0.3
      distance: '0px'
    }, 300
    # Initialize and Configure Magnific Popup Lightbox Plugin
    $('.popup-gallery').magnificPopup
      delegate: 'a'
      type: 'image'
      tLoading: 'Loading image #%curr%...'
      mainClass: 'mfp-img-mobile'
      gallery:
        enabled: true
        navigateByImgClick: true
        preload: [
          0
          1
        ]
      image: tError: '<a href="%url%">The image #%curr%</a> could not be loaded.'
    return
  ) jQuery

一切正常! 不要改变其他任何东西。为您的模板使用正确的 js 文件设置您的 js 清单,然后您就准备好了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-18
    • 2018-05-02
    • 2021-05-07
    • 2019-05-14
    • 2012-04-26
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    相关资源
    最近更新 更多