簡體   English   中英

jQuery更改列內文本的顏色

[英]JQuery changing colour of text within columns

我的網頁中有三列。 每列上都有一組三個正方形,正方形代表一種獨特的顏色。 因此,當用戶單擊第1列中的紅色時,第1列中的文本變為紅色,如果為藍色,則它將變為藍色。 如果用戶單擊第2列中的綠色,則第2列中的文本將變為綠色。

我是jQuery的新手,所以我不確定自己是否做對了,並想知道這是否是最好的方法。

我想知道的是,無論如何都需要進行更改,因此每一列中只有一種樣式稱為“選擇器”。 我還可以更改jQuery,使其不是3個單獨的函數,是否有更簡潔的方法?

謝謝。

是! CSS選擇器都是可重用的! 您不應該創建具有完全相同的屬性和值的多個類!

您需要的所有CSS類.col, .wrapper, .picker

然后在要在多個地方使用代碼時使用jQuery而不是使用div id,請計算元素相對於觸發事件的元素或$(this)

查看小提琴http://jsfiddle.net/WJ5DZ/1/

您可以這樣嘗試:

$(function () {
    $('.picker').css('background-color', function () { //Setup the background color for each picker square.
        return $(this).data('color'); //get its color from data attribute
    }).click(function () { //Chain it through for the click event
        $(this).closest('.content').css({ //get the parent content element where color needs to be applied
            color: $(this).data('color') //set the color as that of the clicked picker.
        });
    });
});

演示

在標記中,提供一個稱為“說content的類以標識其自己的父內容。

<div class='col2 content' id="test1"> <!-- You don't need id if you are using this for selcting. 

刪除所有picker1, 2 CSS規則和剛才的picker

使用closest將確保即使您計划將包裝器添加到選擇器中,仍然會選擇您的實際內容div。

是的,有..將您所有的課程(picker1,picker2)更改為picker並刪除ID(test,test1 ..)

嘗試這個

   $('.picker').each(function(){
      var myColor = $(this).data('color');
      $(this).css({background: myColor })
   });
  $('.picker').click(function(){
     var myColor = $(this).data('color');
     $(this).parent().css({color: myColor});

  });

注意:您不需要each循環內的click事件

在這里擺弄

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM