search
HomeWeb Front-endJS TutorialThe prompt message in the placeholder disappears after the input is clicked_javascript skills

In HTML, placeholder, as an attribute of input, plays the role of occupying a place in the input box and prompting.

However, in some browsers, such as Chrome, when the mouse clicks on the input box, the value of the placeholder does not disappear. It disappears only when the data is entered, which greatly reduces the front-end user experience.

After reading a lot of masters’ methods and writing long js, it seemed a bit difficult, so I thought of the following stupidest method to solve this problem.

html code:

<input type="text" placeholder="多个关键词空格隔开">

When the mouse clicks on the input, the prompt message in the placeholder disappears:

<input type="text" placeholder="多个关键词空格隔开" onfocus="this.placeholder=‘‘" onblur="this.placeholder=‘多个关键词空格隔开‘">

Two ways to implement PlaceHolder

The placeholder attribute is input in HTML5 added. Provide a placeholder on the input that displays a hint (hint) of the expected value of the input field in text form. The field will be displayed when the input is empty.

Such as

<input type="text" name="loginName" placeholder="邮箱/手机号/QQ号">

Current browser support

However, although IE10 supports the placeholder attribute , its performance is inconsistent with other browsers
•In IE10, the placeholder text disappears when the mouse is clicked (gets focus)
•Firefox/Chrome/Safari does not disappear when clicked, but the text disappears when keyboard input

This is quite disgusting, if the placeholder attribute is used. The product manager is still reluctant to give up, and will explain why the prompt text disappears when clicking on it in IE, but the prompt text disappears when typing on the keyboard in Chrome. Ask the front-end engineer to change it to the same form of expression. In view of this, the following two implementations do not use the native placeholder attribute.

Two ways of thinking

1. (Method 1) Use the value of the input as the display text

2. (Method 2) Do not use value, add an extra tag (span) to the body and then cover it with absolute positioning on the input

Both methods have their own advantages and disadvantages. Method one occupies the value attribute of the input, which is required when submitting the form. To do some extra judgment work, the second method uses additional labels.

Method 1

/**
* PlaceHolder组件
* $(input).placeholder({
* word: // @string 提示文本
* color: // @string 文本颜色
* evtType: // @string focus|keydown 触发placeholder的事件类型
* })
*
* NOTE:
* evtType默认是focus,即鼠标点击到输入域时默认文本消失,keydown则模拟HTML5 placeholder属性在Firefox/Chrome里的特征,光标定位到输入域后键盘输入时默认文本才消失。
* 此外,对于HTML5 placeholder属性,IE10+和Firefox/Chrome/Safari的表现形式也不一致,因此内部实现不采用原生placeholder属性
*/
$.fn.placeholder = function(option, callback) {
var settings = $.extend({
word: &#39;&#39;,
color: &#39;#ccc&#39;,
evtType: &#39;focus&#39;
}, option)
function bootstrap($that) {
// some alias 
var word = settings.word
var color = settings.color
var evtType = settings.evtType
// default
var defColor = $that.css(&#39;color&#39;)
var defVal = $that.val()
if (defVal == &#39;&#39; || defVal == word) {
$that.css({color: color}).val(word)
} else {
$that.css({color: defColor})
}
function switchStatus(isDef) {
if (isDef) {
$that.val(&#39;&#39;).css({color: defColor}) 
} else {
$that.val(word).css({color: color})
}
}
function asFocus() {
$that.bind(evtType, function() {
var txt = $that.val()
if (txt == word) {
switchStatus(true)
}
}).bind(&#39;blur&#39;, function() {
var txt = $that.val()
if (txt == &#39;&#39;) {
switchStatus(false)
}
})
}
function asKeydown() {
$that.bind(&#39;focus&#39;, function() {
var elem = $that[0]
var val = $that.val()
if (val == word) {
setTimeout(function() {
// 光标定位到首位
$that.setCursorPosition({index: 0})
}, 10) 
}
})
}
if (evtType == &#39;focus&#39;) {
asFocus()
} else if (evtType == &#39;keydown&#39;) {
asKeydown()
}
// keydown事件里处理placeholder
$that.keydown(function() {
var val = $that.val()
if (val == word) {
switchStatus(true)
}
}).keyup(function() {
var val = $that.val()
if (val == &#39;&#39;) {
switchStatus(false)
$that.setCursorPosition({index: 0})
}
})
}
return this.each(function() {
var $elem = $(this)
bootstrap($elem)
if ($.isFunction(callback)) callback($elem)
})
}

Method 2

$.fn.placeholder = function(option, callback) {
var settings = $.extend({
word: &#39;&#39;,
color: &#39;#999&#39;,
evtType: &#39;focus&#39;,
zIndex: 20,
diffPaddingLeft: 3
}, option)
function bootstrap($that) {
// some alias 
var word = settings.word
var color = settings.color
var evtType = settings.evtType
var zIndex = settings.zIndex
var diffPaddingLeft = settings.diffPaddingLeft
// default css
var width = $that.outerWidth()
var height = $that.outerHeight()
var fontSize = $that.css(&#39;font-size&#39;)
var fontFamily = $that.css(&#39;font-family&#39;)
var paddingLeft = $that.css(&#39;padding-left&#39;)
// process
paddingLeft = parseInt(paddingLeft, 10) + diffPaddingLeft
// redner 
var $placeholder = $(&#39;&#39;)
$placeholder.css({
position: &#39;absolute&#39;,
zIndex: &#39;20&#39;,
color: color,
width: (width - paddingLeft) + &#39;px&#39;,
height: height + &#39;px&#39;,
fontSize: fontSize,
paddingLeft: paddingLeft + &#39;px&#39;,
fontFamily: fontFamily
}).text(word).hide()
// 位置调整 
move()
// textarea 不加line-heihgt属性
if ($that.is(&#39;input&#39;)) {
$placeholder.css({
lineHeight: height + &#39;px&#39;
})
}
$placeholder.appendTo(document.body)
// 内容为空时才显示,比如刷新页面输入域已经填入了内容时
var val = $that.val()
if ( val == &#39;&#39; && $that.is(&#39;:visible&#39;) ) {
$placeholder.show()
}
function hideAndFocus() {
$placeholder.hide()
$that[0].focus()
}
function move() {
var offset = $that.offset()
var top = offset.top
var left = offset.left
$placeholder.css({
top: top,
left: left
})
}
function asFocus() {
$placeholder.click(function() {
hideAndFocus()
// 盖住后无法触发input的click事件,需要模拟点击下
setTimeout(function(){
$that.click()
}, 100)
})
// IE有些bug,原本不用加此句
$that.click(hideAndFocus)
$that.blur(function() {
var txt = $that.val()
if (txt == &#39;&#39;) {
$placeholder.show()
}
})
}
function asKeydown() {
$placeholder.click(function() {
$that[0].focus()
})
}
if (evtType == &#39;focus&#39;) {
asFocus()
} else if (evtType == &#39;keydown&#39;) {
asKeydown()
}
$that.keyup(function() {
var txt = $that.val()
if (txt == &#39;&#39;) {
$placeholder.show()
} else {
$placeholder.hide()
}
})
// 窗口缩放时处理
$(window).resize(function() {
move()
})
// cache
$that.data(&#39;el&#39;, $placeholder)
$that.data(&#39;move&#39;, move)
}
return this.each(function() {
var $elem = $(this)
bootstrap($elem)
if ($.isFunction(callback)) callback($elem)
})
}

Method 2 is not suitable for the following scenarios

1. Initial hiding of input

At this time, the offset of the input cannot be obtained, and the span cannot be positioned on the input.

2. The dom structure of the page containing the input changes

For example, some elements are deleted or added to the page, causing the input to shift upward or downward. At this time, the span has no offset (span is positioned relative to the body). This is disgusting. You can consider using span as a sibling element of input, that is, positioned relative to the inner p (instead of body). But this must force the addition of position:relative to the outer p, which may have a certain impact on the page layout.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft