jQuery-クリックされたリンクに下線を引く
-
05-07-2019 - |
質問
jQueryの良さで手を汚し始めたばかりで、私が取り組んでいる最初のタスクは、リンクをクリックした後に下線を引くことです。当然、同じdiv内の別のリンクがクリックされた後、前のリンクには下線が引かれなくなりました...
よろしく
解決
したがって、基本的に、クリックするとリンクのスタイルを変更する一種のナビゲーションメニューが必要です。まず、下線だけのスタイルを作成します。
<style type="text/css">
a.currentlyActive
{
text-decoration: underline;
}
</style>
変更するコードは...
<a class="navigation" href="#">My First Link</a>
<a class="navigation" href="#">My Second Link</a>
<a class="navigation" href="#">My Third Link</a>
下線ではなく下線にしたいリンクであることを示す、あるタイプのクラスを持ついくつかのリンク。
次に、小さなjQueryマジックを追加して、クリック時にスタイルを適用します。同時に、他のすべてのスタイルを削除する必要があります。
<script type="text/javascript">
$(function() {
$('.navigation').click(function() {
// this removes the underline class from all other ".navigation" links.
$('.navigation').removeClass('currentlyActive');
// this makes the one that was clicked underlined
$(this).addClass('currentlyActive');
});
});
</script>
そして、それだけです。各ステップが何をするのかを説明するために、できる限り冗長にしようとしました。明らかに、クラス名を短くし、コメントを削除して小さくて無駄のないものにすることができます。
他のヒント
$("a").click(function() {
var $this = $(this);
$this.closest("div").find("a").removeClass("underlined");
$this.addClass("underlined");
});
もちろん、リンクに下線を引く「下線付き」というクラスが必要です。
こちらはよりクリーンなバージョンです:
<style type="text/css">
.underline { border-bottom:1px solid #000; }
</style>
<script type="text/javascript">
$(function() {
$('a').click(function() {
$('a').removeClass('underline');
$(this).addClass('underline');
});
});
</script>
所属していません StackOverflow