我正在使用 Python 中的 Dash 构建仪表板。我已经很好地配置了所有图形(它在这里的服务器上运行),下一步是创建一个响应式导航栏和一个页脚。目前看起来像这样:
当我缩小宽度时,它看起来像这样:
我想为此按钮添加功能,以便在单击时隐藏三个链接。我正在尝试使用 JavaScript 和这段代码切换 CSS 'active' 属性:
var toggleButton = document.getElementsByClassName('toggle-button')[0]
var navBarLinks = document.getElementsByClassName('navbar-links')[0]
function toggleFunction() {
navBarLinks.classList.toggle('active')
}
toggleButton.addEventListener('click', toggleFunction)
基本上,当navbar-links
类处于活动状态时,我希望将其设置为display: flex
,而当它不处于活动状态时,我希望将其设置为display: none
Python screen 中定义的 HTML 元素在这里:
html.Nav([
html.Div('Covid-19 global data Dashboard', className='dashboard-title'),
html.A([html.Span(className='bar'),
html.Span(className='bar'),
html.Span(className='bar')],
href='#', className='toggle-button'),
html.Div(
html.Ul([
html.Li(html.A('Linked-In', href='#')),
html.Li(html.A('Source Code', href='#')),
html.Li(html.A('CSV Data', href='#'))
]),
className='navbar-links'),
], className='navbar')
我没想到通过 JavaScript 访问元素会出现问题。在做了一些研究之后,我发现 JavaScript 在执行getElementsByClassName
函数时返回的值为 null。那是因为该函数在呈现页面之前运行(据我所知)。它给了我这个错误:
Dash 回调解决方案(无 Javascript):
import dash
import dash_html_components as html
from dash.dependencies import Output, Input, State
navbar_base_class = "navbar-links"
app = dash.Dash(__name__)
app.layout = html.Nav(
[
html.Div("Covid-19 global data Dashboard", className="dashboard-title"),
html.A(
id="toggle-button",
children=[
html.Span(className="bar"),
html.Span(className="bar"),
html.Span(className="bar"),
],
href="#",
className="toggle-button",
),
html.Div(
id="navbar-links",
children=html.Ul(
children=[
html.Li(html.A("Linked-In", href="#")),
html.Li(html.A("Source Code", href="#")),
html.Li(html.A("CSV Data", href="#")),
],
),
className=navbar_base_class,
),
],
className="navbar",
)
@app.callback(
Output("navbar-links", "className"),
Input("toggle-button", "n_clicks"),
State("navbar-links", "className"),
prevent_initial_call=True,
)
def callback(n_clicks, current_classes):
if "active" in current_classes:
return navbar_base_class
return navbar_base_class + " active"
if __name__ == "__main__":
app.run_server(debug=True)
上面的代码的想法是采取toggle-button
咔嗒Input
和当前值navbar-links
的State
。我们可以使用这个状态来确定我们是否应该添加active
类或删除它。新className
值在回调中返回。
Javascript 解决方案:
window.addEventListener("load", function () {
var toggleButton = document.getElementsByClassName("toggle-button")[0];
var navBarLinks = document.getElementsByClassName("navbar-links")[0];
function toggleFunction() {
navBarLinks.classList.toggle("active");
}
toggleButton.addEventListener("click", toggleFunction);
});
load 事件在整个页面加载后触发,包括所有依赖资源,如样式表和图像。这与 DOMContentLoaded 形成对比,DOMContentLoaded 在页面 DOM 加载后立即触发,无需等待资源完成加载。
https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event
DOMContentLoaded
最好使用,但它只适用于我的load
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句