How to change color: -moz-placeholder with jQuery after installing it?

I ran into a problem where when the background color of the input field changes, the color of the placeholder will mix too much.

I already solved the problem with the readable color of the text in order to correctly return the correct light or dark color.

I can’t understand for life how to set the CSS property for the calculated color for a specific input field. Please give some recommendations?

input:-moz-placeholder { color: #BBBBBB; } input::-webkit-input-placeholder { color: #BBBBBB; } 

The returned color is #222222 , but calling $('#input').css() does not work, as it targets CSS elements directly, not the element.

+4
source share
1 answer

In this solution, I first dynamically add a style block to <head> when the page loads:

 // add style block to the <head> with default placeholder css on page load var defaultColor = 'BBBBBB'; var styleContent = 'input:-moz-placeholder {color: #' + defaultColor + ';} input::-webkit-input-placeholder {color: #' + defaultColor + ';}'; var styleBlock = '<style id="placeholder-style">' + styleContent + '</style>'; $('head').append(styleBlock); 

Then, to change the color of the placeholder text, I just update the contents of the style block:

 var randomColor = Math.floor(Math.random()*16777215).toString(16); styleContent = 'input:-moz-placeholder {color: #' + randomColor + ';} input::-webkit-input-placeholder {color: #' + randomColor + ';}' $('#placeholder-style').text(styleContent); 

Check jsFiddle:

Change text color with jQuery

+6
source

All Articles