我想用 JS 和 CSS 为我的应用程序制作一个可折叠的侧边菜单。这是我的代码:
在views/pages/home.html.erb中我有:
<meta name="viewport" content="width=device-width,initial-scale=1">
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application','data-turbolinks-track': 'reload' %>
<div class = "head">
<div class = "navbar">
<div id="mySidepanel" class="sidepanel">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Clients</a>
<a href="#">Contact</a>
</div>
<button class="openbtn" onclick="openNav()">☰ Toggle Sidepanel</button>
<h1 class = "titles">
<%if current_user%>
¡Bienvenido <%=current_user.first_name%>!
<%else%>
Home
<%end%>
</h1>
<h3 class = "secondary-contact">25 de mayo 1160 Puiggari, Entre Rios, Argentina</h3>
<h3 class = "secondary-contact">TEL. 0343 15-467-5058</h3>
</div>
我的样式表/application.css
.sidepanel {
height: 250px; /* Specify a height */
width: 0; /* 0 width - change this with JavaScript */
position: fixed; /* Stay in place */
z-index: 1; /* Stay on top */
top: 0;
left: 0;
background-color: #111; /* Black*/
overflow-x: hidden; /* Disable horizontal scroll */
padding-top: 60px; /* Place content 60px from the top */
transition: 0.5s; /* 0.5 second transition effect to slide in the sidepanel */
}
/* The sidepanel links */
.sidepanel a {
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 25px;
color: #818181;
display: block;
transition: 0.3s;
}
/* When you mouse over the navigation links, change their color */
.sidepanel a:hover {
color: #f1f1f1;
}
/* Position and style the close button (top right corner) */
.sidepanel .closebtn {
position: absolute;
top: 0;
right: 25px;
font-size: 36px;
margin-left: 50px;
}
/* Style the button that is used to open the sidepanel */
.openbtn {
font-size: 20px;
cursor: pointer;
background-color: #111;
color: white;
padding: 10px 15px;
border: none;
}
.openbtn:hover {
background-color: #444;
}
在 javascript/packs/application.js 中我添加了:
function openNav() {
document.getElementById("x").style.width = "15%";
}
function closeNav() {
document.getElementById("mySidepanel").style.width = "0";
}
问题是当我单击按钮时什么也没有发生。我对 JavaScript 很陌生,找不到我的错误。
最佳答案
你不能直接从dom访问application.js或其他js文件函数。因为 Rails 使用 webpack 来存储您的代码。您可以使用这样的事件;
let openButton = document.querySelectorAll('button.openbtn')
openButton.addEventListener("click", function(event) {
document.getElementById("x").style.width = "15%";
})
let closeButton = document.querySelectorAll('button.closebtn')
closeButton.addEventListener("click", function(event) {
document.getElementById("mySidepanel").style.width = "0";
})
关于JavaScript 无法在 Ruby on Rails 应用程序中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67220395/