2014-02-09 124 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