javascript - 如何使按钮在单击后保持 'active'?

标签 javascript html css button

我目前正在为我的菜单项使用以下代码:

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/

相关文章:

javascript - 如何在html中做出绑定(bind)效果

javascript - 使用 require.js 全局设置 lodash/underscore 模板设置

javascript - 获取提供旧数据的变量

javascript - DropzoneJS : Preview selected image before upload in div as <img>

jquery - CSS 问题 1 图片在谷歌浏览器中丢失

javascript - 如何复用AlpineJs数据?

php - HTML 表单输入 datetime-local 在输入中包含秒数?

javascript - php - 从数据库检索值时如果不为空则启用元素

html - 我将我的 ul li 添加到一个单元格中,但它粘在左边,希望表格显示在中间

css - 如何使用 Tailwind 自定义深色模式颜色