简体   繁体   English

如何使用 css 更改输入占位符文本

[英]How to change input placeholder text with css

I need to change the placeholder text of an input textbox via css.我需要通过 css 更改输入文本框的占位符文本。

Here is the html code:这是 html 代码:

<div class="col">
      <input class="form-control" type="text" placeholder="" id="myID">
</div>

And here is the css one:这是 css 之一:

#myID::placeholder{content:"Type something";}

I can't write the placeholder directly inside the html code and not even with JS.我不能直接在 html 代码中编写占位符,即使使用 JS 也不能。 Is there a way to solve this?有没有办法解决这个问题?

As said in the comments, you can not use pseudo-elements on replaced elements such as input (or images).正如评论中所说,您不能在输入(或图像)等替换元素上使用pseudo-elements So you have to apply it to the wrapping element.因此,您必须将其应用于包装元素。 A method with many downsides that need more solutions and fixed that are caused by the hack:一种具有许多缺点的方法,需要更多解决方案并修复由黑客引起的:

 div { display: inline-block; /* reduces the width to the input */ position: relative; } div::after { content: "type something"; position: absolute; inset: 0; /* uses the same size as the div */ display: flex; align-items: center; justify-content: center; z-index: -1; /* moves the placeholder to the background and makes the inptu clickable */ } input { background: transparent; /* required to see the placehodler while in the background */ } input:focus { background: white; /* hides the placeholder on focus */ }
 <div class="col"> <input class="form-control" type="text" placeholder="" id="myID"> </div>

in JS:在 JS 中:

let myID = document.getElementById('myID');
myID[0].attributes[2].textContent = 'Hello there!';

You will need to check which index of the attributes object of myID exist placeholder.您需要检查 myID 的attributes object 的哪个索引存在占位符。

I tried here directly on the search bar, the placeholder was on the 2 index.我这里直接在搜索栏上试过,占位符在2索引上。 在此处输入图像描述 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM