好的,我是 Javascript 和 jqyery 菜鸟,所以寻求帮助。
我有一个 CSS 菜单栏,用作整个网站的元素。通过为 pressed
元素分配一个类,可以将单个按钮显示为已单击。我拥有的第一个链接显示为已按下。我可以在我的 View 中轻松访问 URL,因此我知道我在哪里,但我希望能够根据 url 的位置在页面加载时动态更改类,因此菜单将显示为该区域选择的内容。我在下面包含了菜单的两个元素。
我想根据变量中的值将 'class'=> 'pressed'
更改为 'class'=> ''
。我该怎么做?
<ul id="menuBar" class="topmenu">
<input type="checkbox" id="css3menu-switcher" class="switchbox">
<label onclick="" class="switch" for="css3menu-switcher"></label>
<li class="topfirst">
<?php
echo $this->Html->link(
$this->Html->image('icons/group.png', array('width' => '20', 'line-height' => '20'))
. ' ' . __('Organisations'),
array('controller' => 'organisations', 'action' => 'index'),
array('escape' => false, 'class'=> 'pressed'));
?>
<ul>
<li> <?php
echo $this->Html->link(
$this->Html->image('icons/group_add.png', array('width' => '20', 'line-height' => '20'))
. ' ' . __('New Organisation'),
array('controller' => 'organisations', 'action' => 'add'),
array('escape' => false));
?></li>
</ul>
</li>
<li class="topmenu">
<?php
echo $this->Html->link(
$this->Html->image('icons/telephone.png', array('width' => '20', 'line-height' => '20'))
. ' ' . __('Contacts'),
array('controller' => 'contacts', 'action' => 'index'),
array('escape' => false));
?>
<ul>
<li> <?php
echo $this->Html->link(
$this->Html->image('icons/telephone_add.png', array('width' => '20', 'line-height' => '20'))
. ' ' . __('New contact'),
array('controller' => 'contacts', 'action' => 'add'),
array('escape' => false, 'class'=> 'unpressed'));
?>
</ul>
</li>
</ul>
以下是两种预期的 html 输出:
<li class="topmenu">
<a href="/dev/oak/trunk/contacts">
<img width="20" alt="" line-height="20" src="/dev/oak/trunk/img/icons/telephone.png">
Contacts
</a></li>
<li class="topmenu">
<a class='pressed' href="/dev/oak/trunk/contacts">
<img width="20" alt="" line-height="20" src="/dev/oak/trunk/img/icons/telephone.png">
Contacts
</a></li>
最佳答案
我认为您完全可以通过 CSS 实现这一点。
您的 HTML 看起来像
<a href="your/link/here" class="changeIfActive"> Some text </a>
将这个类添加到你的 CSS 中
a.changeIfActive{color:white; background:black;}
a.changeIfActive:active{color:black; background:white;}
现在,当用户查看目标页面时,CSS 将使用其 Psudo 类功能更改 CSS 类
关于javascript - 使用 Jquery 即时更改 CSS 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27062140/