2013-02-19 108 views
14

是否可以使用“:: - webkit-input-placeholder”与jQuery来设置占位符文本的颜色?jQuery更改占位符文本颜色

事情是这样的:

$("input::-webkit-input-placeholder").css({"color" : "#b2cde0"}); 
+0

看一看这样的:http://stackoverflow.com/questions/2610497/change-an-inputs-html5-placeholder-color-with -css – 2013-02-19 20:59:31

+0

很高兴看到这个:https://stackoverflow.com/a/20886968/1830909 – QMaster 2018-03-05 23:50:31

回答

41

你真的不能修改伪选择使用JavaScript。您必须修改现有的<style> element

如果可能的话,做一个类:

.your-class::-webkit-input-placeholder { 
    color: #b2cde0 
} 

,并将其添加到元素:

$('input').addClass('your-class'); 
+5

我相信大部分时间的样式占位符文本与jQuery的点将是动态的颜色。 – BenRacicot 2015-02-10 20:39:32

0

我用MaterializeCSS;我用jQuery来更新这样

$(".input-field").css("color", themeColor); 
    $(".input-field>.material-icons").css("color", themeColor); 
    $(".input-field>label").css("color", themeColor); 

见结果输入字段CSS:

https://codepen.io/hiteshsahu/pen/EXoPRq?editors=1000

0

下面是使用jQuery动态设置伪元素风格的例子 - 这是创建的问题<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>