The color of the default text under the style control input::-webkit-input-placeholder{color:#AAAAAA;} can be added at most, but at low"/> The color of the default text under the style control input::-webkit-input-placeholder{color:#AAAAAA;} can be added at most, but at low">
search
HomeWeb Front-endJS TutorialExample code of jQuery encapsulating placeholder
Example code of jQuery encapsulating placeholderJul 21, 2017 pm 05:27 PM
firefoxjqueryplaceholder

The default prompt text of the input box on the page generally uses the placeholder attribute, that is:

<input>

The color of the default text under style control can be added at most

input::-webkit-input-placeholder{color:#AAAAAA;}

But this placeholder attribute is not supported in lower version browsers, so it is really necessary to implement placeholder in lower version browsers If you have the same effect, you need to write a plug-in for compatibility. Let’s explain in detail how to use jquery to achieve this simulation effect.

To achieve this simulation effect, the general calling method of the page:

$('input').placeholder();

First, write the general structure of the jquery plug-in:

;(function($){
    $.fn.placeholder = function(){//实现placeholder的代码    }
})(jQuery)

Next we have to determine whether the browser supports the placeholder attribute.

;(function($){
    $.fn.placeholder = function(){this.each(function(){var _this = this;var supportPlaceholder = 'placeholder' in document.createElement('input');if(!supportPlaceholder){//不支持placeholder属性的操作}
        });
    }
})(jQuery)

We need to support chain operations, as follows:

;(function($){
    $.fn.placeholder = function(){         return this.each(function(){var _this = this;var supportPlaceholder = 'placeholder' in document.createElement('input');if(!supportPlaceholder){//不支持placeholder属性的操作}
        });
    }
})(jQuery)

Default configuration items:

options = $.extend({
    placeholderColor:'#aaaaaa',
    isSpan:false, //是否使用插入span标签模拟placeholder的方式,默认是不需要onInput:true //实时监听输入框},options);

If you do not need to use span to simulate the placeholder effect, then you need to judge by the value of the input box, as follows:

if(!options.isSpan){
    $(_this).focus(function () {var pattern = new RegExp("^" + defaultValue + "$|^$");
        pattern.test($(_this).val()) && $(_this).val('').css('color', defaultColor);
    }).blur(function () {if($(_this).val() == defaultValue) {
            $(_this).css('color', defaultColor);
        }else if($(_this).val().length == 0) {
            $(_this).val(defaultValue).css('color', options.placeholderColor)
        }
    }).trigger('blur');
}

If you need the same span tag to simulate the placeholder effect, the code is as follows:

var $simulationSpan = $('<span>'+defaultValue+'</span>');
$simulationSpan.css({'position':'absolute','display':'inline-block','overflow':'hidden','width':$(_this).outerWidth(),'height':$(_this).outerHeight(),'color':options.placeholderColor,'margin-left':$(_this).css('margin-left'),'margin-top':$(_this).css('margin-top'),'padding-left':parseInt($(_this).css('padding-left')) + 2 + 'px','padding-top':_this.nodeName.toLowerCase() == 'textarea' ? parseInt($(_this).css('padding-top')) + 2 : 0,'line-height':_this.nodeName.toLowerCase() == 'textarea' ? $(_this).css('line-weight') : $(_this).outerHeight() + 'px','font-size':$(_this).css('font-size'),'font-family':$(_this).css('font-family'),'font-weight':$(_this).css('font-weight')
});//通过before把当前$simulationSpan添加到$(_this)前面,并让$(_this)聚焦$(_this).before($simulationSpan.click(function () {
    $(_this).trigger('focus');
}));//当前输入框聚焦文本内容不为空时,模拟span隐藏$(_this).val().length != 0 && $simulationSpan.hide();if (options.onInput) {//绑定oninput/onpropertychange事件var inputChangeEvent = typeof(_this.oninput) == 'object' ? 'input' : 'propertychange';
    $(_this).bind(inputChangeEvent, function () {
        $simulationSpan[0].style.display = $(_this).val().length != 0 ? 'none' : 'inline-block';
    });
}else {
    $(_this).focus(function () {
        $simulationSpan.hide();
    }).blur(function () {/^$/.test($(_this).val()) && $simulationSpan.show();
    });
};

Overall code:

;(function($){
    $.fn.placeholder = function(options){
        options = $.extend({
            placeholderColor:'#aaaaaa',
            isSpan:false, //是否使用插入span标签模拟placeholder的方式,默认是不需要onInput:true //实时监听输入框        },options);         return this.each(function(){var _this = this;var supportPlaceholder = 'placeholder' in document.createElement('input');if(!supportPlaceholder){//不支持placeholder属性的操作var defaultValue = $(_this).attr('placeholder');var defaultColor = $(_this).css('color');if(!options.isSpan){
                    $(_this).focus(function () {var pattern = new RegExp("^" + defaultValue + "$|^$");
                        pattern.test($(_this).val()) && $(_this).val('').css('color', defaultColor);
                    }).blur(function () {if($(_this).val() == defaultValue) {
                            $(_this).css('color', defaultColor);
                        }else if($(_this).val().length == 0) {
                            $(_this).val(defaultValue).css('color', options.placeholderColor)
                        }
                    }).trigger('blur');
                }else{var $simulationSpan = $('<span>'+defaultValue+'</span>');
                    $simulationSpan.css({'position':'absolute','display':'inline-block','overflow':'hidden','width':$(_this).outerWidth(),'height':$(_this).outerHeight(),'color':options.placeholderColor,'margin-left':$(_this).css('margin-left'),'margin-top':$(_this).css('margin-top'),'padding-left':parseInt($(_this).css('padding-left')) + 2 + 'px','padding-top':_this.nodeName.toLowerCase() == 'textarea' ? parseInt($(_this).css('padding-top')) + 2 : 0,'line-height':_this.nodeName.toLowerCase() == 'textarea' ? $(_this).css('line-weight') : $(_this).outerHeight() + 'px','font-size':$(_this).css('font-size'),'font-family':$(_this).css('font-family'),'font-weight':$(_this).css('font-weight')
                    });//通过before把当前$simulationSpan添加到$(_this)前面,并让$(_this)聚焦$(_this).before($simulationSpan.click(function () {
                        $(_this).trigger('focus');
                    }));//当前输入框聚焦文本内容不为空时,模拟span隐藏$(_this).val().length != 0 && $simulationSpan.hide();if (options.onInput) {//绑定oninput/onpropertychange事件var inputChangeEvent = typeof(_this.oninput) == 'object' ? 'input' : 'propertychange';
                        $(_this).bind(inputChangeEvent, function () {
                            $simulationSpan[0].style.display = $(_this).val().length != 0 ? 'none' : 'inline-block';
                        });
                    }else {
                        $(_this).focus(function () {
                            $simulationSpan.hide();
                        }).blur(function () {/^$/.test($(_this).val()) && $simulationSpan.show();
                        });
                    };
                }
            }
        });
    }
})(jQuery);

The calling method needs to pass span To simulate using tags:

$("#username").placeholder({
    isSpan:true});

The above is the detailed content of Example code of jQuery encapsulating placeholder. For more information, please follow other related articles on the PHP Chinese website!

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
Ubuntu Linux中如何删除Firefox Snap?Ubuntu Linux中如何删除Firefox Snap?Feb 21, 2024 pm 07:00 PM

要在UbuntuLinux中删除FirefoxSnap,可以按照以下步骤进行操作:打开终端并以管理员身份登录到Ubuntu系统。运行以下命令以卸载FirefoxSnap:sudosnapremovefirefox系统将提示你输入管理员密码。输入密码并按下Enter键以确认。等待命令执行完成。一旦完成,FirefoxSnap将被完全删除。请注意,这将删除通过Snap包管理器安装的Firefox版本。如果你通过其他方式(如APT包管理器)安装了另一个版本的Firefox,则不会受到影响。通过以上步骤

jquery实现多少秒后隐藏图片jquery实现多少秒后隐藏图片Apr 20, 2022 pm 05:33 PM

实现方法:1、用“$("img").delay(毫秒数).fadeOut()”语句,delay()设置延迟秒数;2、用“setTimeout(function(){ $("img").hide(); },毫秒值);”语句,通过定时器来延迟。

jquery怎么修改min-height样式jquery怎么修改min-height样式Apr 20, 2022 pm 12:19 PM

修改方法:1、用css()设置新样式,语法“$(元素).css("min-height","新值")”;2、用attr(),通过设置style属性来添加新样式,语法“$(元素).attr("style","min-height:新值")”。

axios与jquery的区别是什么axios与jquery的区别是什么Apr 20, 2022 pm 06:18 PM

区别:1、axios是一个异步请求框架,用于封装底层的XMLHttpRequest,而jquery是一个JavaScript库,只是顺便封装了dom操作;2、axios是基于承诺对象的,可以用承诺对象中的方法,而jquery不基于承诺对象。

jquery怎么在body中增加元素jquery怎么在body中增加元素Apr 22, 2022 am 11:13 AM

增加元素的方法:1、用append(),语法“$("body").append(新元素)”,可向body内部的末尾处增加元素;2、用prepend(),语法“$("body").prepend(新元素)”,可向body内部的开始处增加元素。

jquery怎么删除div内所有子元素jquery怎么删除div内所有子元素Apr 21, 2022 pm 07:08 PM

删除方法:1、用empty(),语法“$("div").empty();”,可删除所有子节点和内容;2、用children()和remove(),语法“$("div").children().remove();”,只删除子元素,不删除内容。

mozilla firefox可以卸载吗mozilla firefox可以卸载吗Mar 15, 2023 pm 04:40 PM

mozilla firefox可以卸载;firefox属于第三方浏览器,如果不需要,完全可以卸载。卸载方法:1、在开始菜单中,依次点击“Windwos系统”-“控制面板”;2、在“控制面板”界面中,点击“程序和功能”;3、在新界面中,找到并双击火狐浏览器图标;4、在卸载弹窗中,点击“下一步”;5、点击“卸载”即可。

jquery怎么去掉只读属性jquery怎么去掉只读属性Apr 20, 2022 pm 07:55 PM

去掉方法:1、用“$(selector).removeAttr("readonly")”语句删除readonly属性;2、用“$(selector).attr("readonly",false)”将readonly属性的值设置为false。

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

Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment