How JQuery can parse colors in text?
How to parse colors in text, if i type #40464f , i would like catch the color and apply it some CSS.
I know how to do that with added markup,
<span data-color=""&开发者_运维问答gt; #40464f </span>
for example.
But i would like to know if its possible to do that automatically without the needed to add markups manually ?
Not really knowing what's asked, I'll just provide a way to match (HEX) colors within an HTML element.
Given HTML:
<p id="subject">
Here is a color: #fff. Red is #ff0000 while #9ab57d is another color.
</p>
Use JS:
$(function() {
var m = $('#subject').text().match(/#(?:[0-9a-f]{3}){1,2}/gi);
// ['#fff', '#ff0000', '#9ab57d']
$.each(m, function(i, v) {
// `v` is each color...
});
});
(Demo)
Update
Demo where the colors are actually used:
HTML:
<p id="subject">
Here is a color: #fff. Red is #ff0000 while #9ab57d is another color.
</p>
<ol id="result"></ol>
JS:
$(function() {
var m = $('#subject').text().match(/#(?:[0-9a-f]{3}){1,2}/gi),
$result = $('#result');
$.each(m, function(i, v) {
$('<li />').text(v).css('background-color', v).appendTo($result);
});
});
Update #2
Based on comments, replacing inline (demo):
HTML:
<p id="subject">
Nous obtenons les 2 couleurs suivantes : #40464f & #0f131a
</p>
JS:
$(function() {
var $subject = $('#subject'),
str = $subject.html();
str = str.replace(/#(?:[0-9a-f]{3}){1,2}/gim, "<span style=\"background-color: $&;\">$&</span>");
$subject.html(str);
});
Since I guess it's the text within the span you wish to check against I think that regexp matching is the way you have to go.
Here is a filter that allows regexp to be used for selecting elements.
http://james.padolsey.com/javascript/regex-selector-for-jquery/
Working Example on JSFiddle.net
<input /> <button>Change</button> <div></div>
<script>
$(function(){
$('button').click(function(){
$('div').css('background-color', $('input').val());
});
});
</script>
Or if it is the text color you wish to change just use .css('color', $('input').val())
Also, Note that your selectors should be better than mine!
精彩评论