![](/img/trans.png)
[英]How to change the color or background-color of the nav link using jquery?
[英]jQuery change background-color on click using a variable
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>...
使navbar項目background-color = section background-color
基本圖形示例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'));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.