最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get font color of clicked text? - Stack Overflow

programmeradmin1浏览0评论

The following example will get the color of the word "Here" when you double click to select it. I need to get the color when you simply single click inside of it. I also need a way to get the color the of text which does not have a <font color=""></font> tag surrounding it, the rgb value maybe? Basically, when you single click anywhere on the string, I need get the color of the font of the word you clicked on. How can this be acplished?

/

HTML:

<div contentEditable="true"><font color="gold">Here</font> is some text.</div>

JS:

$('div').mousedown(function() {
  var selected = window.getSelection().focusNode.parentNode;
  var color = $(selected).attr('color');
  console.log(color);
});

UPDATE: Using event.target with css('color') works as I expected: /

$('div').mousedown(function(event) {
    var clicked = event.target;
    var color = $(clicked).css('color');
    console.log(color);
});

The following example will get the color of the word "Here" when you double click to select it. I need to get the color when you simply single click inside of it. I also need a way to get the color the of text which does not have a <font color=""></font> tag surrounding it, the rgb value maybe? Basically, when you single click anywhere on the string, I need get the color of the font of the word you clicked on. How can this be acplished?

https://jsfiddle/7ng9j49t/

HTML:

<div contentEditable="true"><font color="gold">Here</font> is some text.</div>

JS:

$('div').mousedown(function() {
  var selected = window.getSelection().focusNode.parentNode;
  var color = $(selected).attr('color');
  console.log(color);
});

UPDATE: Using event.target with css('color') works as I expected: https://jsfiddle/fof2u7L9/

$('div').mousedown(function(event) {
    var clicked = event.target;
    var color = $(clicked).css('color');
    console.log(color);
});
Share Improve this question edited May 8, 2017 at 19:56 asked May 8, 2017 at 19:07 user7347805user7347805 3
  • 4 Side note, don't use the <font> element – j08691 Commented May 8, 2017 at 19:08
  • I know and thanks but that is what execmand / contenteditable / designmode use. – user7347805 Commented May 8, 2017 at 19:09
  • 2 Possible duplicate of How do I get the perceived styling of a text node? – Heretic Monkey Commented May 8, 2017 at 19:18
Add a ment  | 

2 Answers 2

Reset to default 8
  • <font> tag is deprecated.
  • To get an absolute color, use window.getComputedStyle():

Code:

var selected = /* get selected element */;
var color = window.getComputedStyle(selected).getPropertyValue("color");

Use event.target:

$('div').mousedown(function(evt) {
    var clicked = evt.target;
    var color = $(clicked).attr('color');
    console.log(color);
});
发布评论

评论列表(0)

  1. 暂无评论