我目前正在为我的菜单项使用以下代码:
HTML
<li>
<a id="About" class="button" href="About Us.cshtml">About Us</a>
</li>
<li style="margin-left: 30px;">
<a id="Services" class="button" href="Services.cshtml">Services</a>
</li>
<li style="margin-left: 30px;">
<a id="Contact" class="button" href="Contact Us.cshtml">Contact Us</a>
</li>
CSS
#About {background-image: url(../Buttons/About.png); width: 87px;}
#Services {background-image: url(../Buttons/Services.png); width: 112px;}
#Contact {background-image: url(../Buttons/Contact.png); width: 117px;}
a.button {height: 20px; display: inline-block; background-repeat: no-repeat}
a.button:hover {background-position: 0 -20px;}
a.button:active {background-position: 0 -40px;}
我需要让按钮在单击按钮和页面加载/刷新等后保持“事件”状态。
如果解决方案需要 javascript,请记住我是一名业余爱好者,因此我需要任何通俗易懂的解释(最好有示例)。
最佳答案
您需要确定您当前所在的页面。
var page = window.location.href;
page = page.substr((page.lastIndexOf('/') + 1));
page = page.split('.');
page = page[0];
//At this point you will have the current page only with no extension or query paramaters
//I.E. "About Us"
page = page.toUpperCase();
//This accounts for upper or lower casing of urls by browsers.
switch(page) {
case "ABOUT US":
$('#About').addClass('< name of active button class >');
break;
case "SERVICES":
$('#Services').addClass('< name of active button class >');
break;
case "CONTACT US":
$('#Contact').addClass('< name of active button class >');
break;
}
如果您不使用 jQuery,请替换此行:
$('#< element name >').addClass('< name of active button class >');
用这一行:
document.getElementById("< element name >").className += " < name of active button class >";
希望这对您有所帮助。
关于javascript - 如何使按钮在单击后保持 'active'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13650053/