如何动态改变所选择的网页的菜单项的颜色? [英] How to dynamically change the color of the selected menu item of a web page?

查看:186
本文介绍了如何动态改变所选择的网页的菜单项的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是开发网页的新手。我正在寻找创建类似于stackoverflow.com的菜单(像问题,标签,用户上面显示)。如何更改所选菜单的颜色(例如,点击时问题的背景颜色变为橙色)?

I am new to developing web pages. I am looking to create menus similar to the ones in stackoverflow.com (like Questions, Tags, Users shown above). How do I change the color of the selected menu (for example, the background color of the Question changes to orange when 'clicked')?

我已经设法改变颜色,同时悬停(使用CSS),因为这很简单,但我遇到了麻烦。

I have managed to change the color while hovering (using CSS) as that was simple, but I am having trouble with this.

我可以使用CSS来实现改变点击项目颜色的效果吗?

Can I achieve this effect of changing the color of a clicked item using only CSS?

推荐答案

适用于类活动和悬停的样式:

Set the styles for class active and hover:

比起在服务器端,您需要使li活跃。
所以当你绘制菜单时,你应该知道加载哪个页面并将其设置为:

Than you need to make the li active, on the server side. So when you are drawing the menu, you should know which page is loaded and set it to:

 <li class="active">Question</li>
 <li>Tags</li>
 <li>Users</li>

但是如果您正在更改内容而不重新加载,则无法更改在服务器上设置活动LI元素,您需要使用javascript:

But if you are changing the content without reloading, you cannot change set the active li element on the server, you need to use javascript:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<style>
  .menu{width: 300px; height: 25; font-size: 18px;}
  .menu li{list-style: none; float: left; margin-right: 4px; padding: 5px;}
  .menu li:hover, .menu li.active {
        background-color: #f90;
    }
</style>
</head>
<body>

<ul class="menu">
<li>Item 1</li>
<li class="active">Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
</ul>

<script type="text/javascript">

var make_button_active = function()
{
  //Get item siblings
  var siblings =($(this).siblings());

  //Remove active class on all buttons
  siblings.each(function (index)
    {
      $(this).removeClass('active');
    }
  )


  //Add the clicked button class
  $(this).addClass('active');
}

//Attach events to menu
$(document).ready(
  function()
  {
    $(".menu li").click(make_button_active);
  }  
)

</script>
</body>

</html>

这篇关于如何动态改变所选择的网页的菜单项的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆