2014-02-09 38 views
0

我有一個jQuery和HTML的代碼。該代碼假設用戶可以在單擊時更改文本顏色,並選擇文本應該更改的顏色。 但是,我有點麻煩。當我在textarea中寫藍色時,它總是將文本顏色改爲黑色。第二個問題是當我點擊「顯示文本的顏色」時,它會用rgb顯示顏色。有沒有辦法讓它顯示顏色的名字?無法更改文字顏色與jQuery同時獲取用戶顏色

下面是代碼:

<!DOCTYPE html> 
<html> 

<head> 
<title>Change Color of Text</title> 
<script src="jquery-1.11.0.min.js"></script> 
<script> 
$(document).ready(function() { 
var TextColor = $("#text").css("color"); 
var ColorToChangeTo = $("#ColorToChange").text(); 
$("#GetColor").click(function() { 
$("#ShowColor").text("The text color is " + TextColor); 
}); 
$("#ChangeColor").click(function() { 
$("#text").css("color", ColorToChangeTo); 
}); 
}); 
</script> 
</head> 

<body dir="ltr" style="font-family: calibri;"> 
<center> 
<div id="text" style="color: red;"> 
Hello, I am a text. 
<br>Click the button below to see what is my color. If you want to change my color, 
<br>enter the color that you want me to be displayed in and push the button "Change text color!" 
    </div> 
    <input type="button" id="GetColor" value="Show me the text's color!" /> 
    <br> 
    <div id="ShowColor"></div> 
    <input type="text" id="ColorToChange" /> 
    <br> 
    <input type="button" id="ChangeColor" value="Change text color!" /> 
</center> 
</body> 

</html> 

回答

1

這應該解決您的第一個問題:

<!DOCTYPE html> 
<html> 
<head> 
<title>Change Color of Text</title> 
<script> 
$(document).ready(function() { 

$("#GetColor").click(function() { 
    var TextColor = $("#text").css("color"); 
    $("#ShowColor").text("The text color is " + TextColor); 
}); 
$("#ChangeColor").click(function() { 
    var ColorToChangeTo = $("#ColorToChange").val(); 
    $("#text").css("color", ColorToChangeTo); 
}); 
}); 
</script> 
</head> 

<body dir="ltr" style="font-family: calibri;"> 
<center> 
<div id="text" style="color: red;"> 
Hello, I am a text. 
<br>Click the button below to see what is my color. If you want to change my color, 
<br>enter the color that you want me to be displayed in and push the button "Change text color!" 
    </div> 
    <input type="button" id="GetColor" value="Show me the text's color!" /> 
    <br> 
    <div id="ShowColor"></div> 
    <input type="text" id="ColorToChange" /> 
    <br> 
    <input type="button" id="ChangeColor" value="Change text color!" /> 
</center> 
</body> 

</html> 

特別是:

$("#ChangeColor").click(function() { 
    var ColorToChangeTo = $("#ColorToChange").val(); 
    $("#text").css("color", ColorToChangeTo); 
}); 

你必須讓顏色由用戶插入每次按鈕被點擊(如果您只在頁面加載時運行$("#ColorToChange").val();,它將保持在特定時刻的價值,並不會刷新)。

要獲取輸入內容,請使用.val()而不是.text()。第一個讀取輸入的值,第二個是用於檢索標籤(<span>This is text that would be retrieved by .text()</span>

與第二請求中的文本:

有沒有什麼辦法讓它顯示顏色的名稱?

Returning name of colors using jQuery

+0

非常感謝您! – Hagaymosko

+0

不客氣! :) – Bobby

0

你可以做到這一點與color_classifier.js插件。它運作良好,並返回名稱最近的顏色的名稱。

這是一個問題,可以預先在回答#herehere