jos*_*krz 2 javascript internet-explorer
我有一些Javascript代码,用于检查浏览器是否支持占位符,如果不支持占位符,则会自行创建.现在这适用于一些较旧的浏览器,但不是全部,尤其是IE.
我需要做的就是获取"占位符"值,此时IE9中的占位符是"未定义".
这是我的代码:
//Test if Placeholders are supported
var test = document.createElement("input");
if ("placeholder" in test) {
var testholder = true;
}
else {
var testholder = false;
}
//Fix unsupported placeholders
function placeHolder(id)
{
var demo = document.getElementById(id);
demo.className = "fix-hint";
demo.value = demo.placeholder;
demo.onfocus = function()
{
if (this.className == "fix-hint")
{
this.value = ""; this.className = "fix-nohint";
}
};
demo.onblur = function()
{
if (this.value === "")
{
this.className = "fix-hint"; this.value = demo.placeholder;
}
};
return false;
Run Code Online (Sandbox Code Playgroud)
我正在使用0%Jquery,我觉得解决小问题太笨重了,而且我想学习纯Javascript.Modernizr也是不行的虽然我可能会在某些时候使用它.
UPDATE
这是工作代码.在IE 8和9中测试过.(函数调用在"placeSupport"的if/else范围内.)
//Check if placeholders are supported
placeholderSupport = ("placeholder" in document.createElement("input"));
if(!placeholderSupport){
var placeSupport = false;
}else{
var placeSupport = true;}
//Support placeholders in older browsers
function placeHolder (id)
{
var el = document.getElementById(id);
var placeholder = el.getAttribute("placeholder");
el.onfocus = function ()
{
if(this.value == placeholder)
{
this.value = '';
this.className = "fix-nohint";
}
};
el.onblur = function ()
{
if(this.value.length == 0)
{
this.value = placeholder;
this.className = "fix-hint";
}
};
el.onblur();
Run Code Online (Sandbox Code Playgroud)
}
如果您不确定是否能够使用某些功能/属性,请尝试使用caniuse.com - 您会注意到IE9中没有占位符.
尝试使用 getAttribute("placeholder")
getAttribute()返回指定元素上的named属性的值.如果named属性不存在,则返回的值将为null或""(空字符串); 有关详细信息,请参阅
HTML
<input id="demo" placeholder="Rawr" />
Run Code Online (Sandbox Code Playgroud)
JavaScript的
var placeholder = document.getElementById("demo").getAttribute("placeholder");
console.log(placeholder);
Run Code Online (Sandbox Code Playgroud)