使用jQuery和"::-webkit-input-placeholder"是否可以设置占位符文本的颜色?
类似于这样:
$("input::-webkit-input-placeholder").css({"color" : "#b2cde0"});
使用jQuery和"::-webkit-input-placeholder"是否可以设置占位符文本的颜色?
类似于这样:
$("input::-webkit-input-placeholder").css({"color" : "#b2cde0"});
您无法使用JavaScript直接修改伪选择器。您需要修改现有的<style>
元素。
如果可能,请创建一个类:
.your-class::-webkit-input-placeholder {
color: #b2cde0
}
并将其添加到元素中:
$('input').addClass('your-class');
$('body').append('<style>.my_class::placeholder{color:red}</style>')
只需使用my_class和color来指定占位符。
拥有一个通用的函数很方便:
function change_placeholder_color(target_class, color_choice) {
$("body").append("<style>" + target_class + "::placeholder{color:" + color_choice + "}</style>")
}
使用方法:
change_placeholder_color('.my_input', 'red')
$('input').append('<style>.my_class::placeholder{color:red}</style>').addClass('my_class');
- mikeypie只需添加此代码。它将继承输入框[type=text]:focus的颜色并应用新颜色。
.your-class ::placeholder{ color: inherit;}
<style>
元素,将其文本内容设置为所需的样式声明,并将其附加到文档中即可。<!doctype html>
<html>
<head>
<title>Dynamic Pseudo-element Styles</title>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script>
$(document).ready(function() {
createStyles();
$('#slider-font-size').on('change', createStyles);
function createStyles() {
// remove previous styles
$('#ph-styles').remove();
// create a new <style> element, set its ID
var $style = $('<style>').attr('id', 'ph-styles');
// get the value of the font-size control
var fontSize = parseInt($('#slider-font-size').val(), 10);
// create the style string: it's the text node
// of our <style> element
$style.text(
'::placeholder { ' +
'font-family: "Times New Roman", serif;' +
'font-size: ' + fontSize + 'px;' +
'}');
// append it to the <head> of our document
$style.appendTo('head');
}
});
</script>
</head>
<body>
<form>
<!-- uses the ::placeholder pseudo-element style in modern Chrome/Firefox -->
<input type="text" placeholder="Placeholder text..."><br>
<!-- add a bit of dynamism: set the placeholder font size -->
<input id="slider-font-size" type="range" min="10" max="24">
</form>
</body>
</html>
我正在使用MaterializeCSS;我使用Jquery来更新输入字段的CSS,就像这样
$(".input-field").css("color", themeColor);
$(".input-field>.material-icons").css("color", themeColor);
$(".input-field>label").css("color", themeColor);
查看结果: