我想更改用戶所在頁面的背景顏色。我嘗試了一些代碼,但它們不起作用。我的 js 代碼在不同的檔案中,它正在將選單加載到某些頁面。
$(function(){
$("#menu-nav").load("menu.html");
$("#footer").load("footer.html");
})
/* The menu code is in another file */
<div class="menu-nav">
<ul id="nav">
<li><a id="homeLink" href="index.html">home</a></li>
<li><a id="pessoal" class="a-borda" href="pessoal.html">pessoal</a></li>
<li><a id="galeria" href="galeria.html">galeria</a></li>
</ul>
</div>
我試過的代碼,但沒有添加類
var section = window.location.pathname;
if (section == "/index.html"){$("#homeLink").attr("class", "active");}
CSS:
.active {
background-color: red;
}
也嘗試使用 .addClass( className ),但不添加類。我不知道我將檔案與 Jquery 一起帶來的事實是否會干擾該程序,或者我是否使用了錯誤的語法。
uj5u.com熱心網友回復:
您可以根據頁面動態添加類
$(document).ready(function() {
let section = window.location.pathname.substring(1);
$(`a[href='${section}']`).addClass("active");
})
uj5u.com熱心網友回復:
您需要將您的包裝var section = window.location.pathname; ... if (section == "/index.html"){$("#homeLink").attr("class", "active");}成$(function(){. 這讓腳本等到 DOM 完成加載。
$(function(){
var section = window.location.pathname;
//Changed the section to /js as the script is run from https://stacksnippets.net/js
if (section == "/js") {
$("#homeLink").addClass("active");
}
})
.active {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="menu-nav">
<ul id="nav">
<li><a id="homeLink" href="index.html">home</a></li>
<li><a id="pessoal" class="a-borda" href="pessoal.html">pessoal</a></li>
<li><a id="galeria" href="galeria.html">galeria</a></li>
</ul>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/475385.html
下一篇:jQuery檢查表中的所有復選框
