javascript - jQuery 使用变量在单击时更改背景颜色

标签 javascript jquery navbar nav

场景

3 个导航项

<a href='#one'></a> <a href='#two'></a> <a href='#three'></a>

3 个部分

<section id='one'></section>
<section id='two'></section>
<section id='three'></section>...

使导航栏项目背景颜色=部分背景颜色

基本图形示例 http://i.stack.imgur.com/3VTBG.jpg

JSFiddle http://jsfiddle.net/kolorweb/r871bzz3/

我已经设法使用一个检索部分背景颜色的变量来实现动态颜色变化。

但是如何在单击另一个导航项时删除此背景色属性..

$('nav ul li a').click(function() {
  $('nav ul li a').removeClass('active');
  $(this).addClass('active');

  // gets #''
  var section_id = $(this).attr('href');

  // this is the variable I want to apply to the relevant nav a on click.
  var section_color = $(section_id).css('background-color');

  // applying variable to the nav item that has been clicked  
  $(this).css('background-color', section_color);

  // HOW DO I THEN REMOVE THIS PROPERTY WHEN ANOTHER NAV ITEM IS CLICKED?




});
nav ul li {
  list-style: none;
  display: inline;
}
nav a {
  text-decoration: none;
  padding: 10px 20px;
}
.active {
  background-color: tomato;
}
#one {
  width: 100vw;
  height: 100px;
  background-color: tomato;
}
#two {
  width: 100vw;
  height: 100px;
  background-color: pink;
}
#three {
  width: 100vw;
  height: 100px;
  background-color: steelblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<nav>
  <ul>
    <li><a href="#one">one</a>
    </li>
    <li><a href="#two">two</a>
    </li>
    <li><a href="#three">three</a>
    </li>
  </ul>
</nav>

<section id="one">One</section>
<section id="two">Two</section>
<section id="three">Three</section>

最佳答案

在应用到事件的之后不要从其他中删除,但在之前从所有中删除:

$('nav ul li a').click(function() {
  $('nav ul li a').removeClass('active');
  $(this).addClass('active');

  // gets #''
  var section_id = $(this).attr('href');

  // this is the variable I want to apply to the relevant nav a on click.
  var section_color = $(section_id).css('background-color');

  // remove from all
  $('nav ul li a').css('background-color', '');

  // applying variable to the nav item that has been clicked  
  $(this).css('background-color', section_color);

});

还有一个短链版本:

$('nav ul li a').click(function() {
  $('nav ul li a').removeClass('active').css('background-color', '');
  $(this).addClass('active').css('background-color', $($(this).attr('href')).css('background-color'));
});

关于javascript - jQuery 使用变量在单击时更改背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28126918/

相关文章:

javascript - jquery 查找下一个带有类的元素

jQuery ajax 不适用于 ie8

asp.net - JQuery 或任何其他 Javascript 库。用于开发 Web 应用程序

javascript - 如何让导航栏下拉菜单与主体重叠?

jquery - 如何在页面中使用多个引导折叠导航栏?

css - 导航栏向右移动 - 为什么?

javascript - 将元素内的 Html DOM 作为字符串传递给 AngularJS Controller

javascript - 传递一串less给less.js并接收css?

javascript - Primeng确认对话框: Hide the Button after Confirmation

javascript - 在 MVC 的 JavaScript 中计算函数