Javascript仅在放置在视图页面中时才有效

时间:2016-07-18 22:26:50

标签: javascript ruby-on-rails

我的rails应用程序仅在放入视图页面中的脚本标记内时使用Js代码,而不是将其放入asset js文件夹中的js文件中。

以下是代码:

<script type="text/javascript">
var menu = document.querySelectorAll(".side-menu")[0],
closedPosition = menu.offsetWidth - 15; //make sure there are 15 pixels showing

Draggable.create(menu, {
  type:"x",
  throwProps:true, //enables the momentum-based flicking (requires ThrowPropsPlugin)
  edgeResistance: 0.9, //you can set this to 1 if you don't want the user to be able to drag past the snap point. This controls how much resistance there is after it hits the max/min.
  maxDuration:0.3, //don't let the animation duration exceed 0.3 second (you can tweak this too of course)
  bounds: {maxX:closedPosition, minX:0}, 
  onClick: function() { //when the user clicks/taps on the menu without dragging, we'll toggle it...
    if (this.target._gsTransform.x === closedPosition) { 
      TweenLite.to(this.target, 0.3, {x:0});
    } else {
      TweenLite.to(this.target, 0.3, {x:closedPosition});
    }
  },
  snap: {
    x: [0, closedPosition]
  }
});
</script>

这是layouts文件夹中的application.html.erb

<!DOCTYPE html>
<html>
<head>
  <title>CityScape</title>
<link href='http://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Roboto+Slab' rel='stylesheet' type='text/css'>
<meta name="viewport" content="width=device-width, initial-scale=1">

  <%= javascript_include_tag 'https://cdnjs.cloudflare.com/ajax/libs/gsap/1.17.0/TweenMax.min.js'%>
  <%= javascript_include_tag 'https://cdnjs.cloudflare.com/ajax/libs/gsap/1.17.0/utils/Draggable.min.js'%>


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

  <%= csrf_meta_tags %>
</head>
<body>

<%= yield %>

</body>
</html>

问题是:如何让它从资产中运作?

2 个答案:

答案 0 :(得分:1)

因为,您需要在html文件中使用js代码创建指向文件的链接,例如:

<script src="/assets/js/jquery/1.7.1/jquery.min.js"></script>

答案 1 :(得分:0)

在您的application.html.erb文件中,请务必在<head>部分中包含此代码:<%= javascript_include_tag "application", "data-turbolinks-track" => true %>