【问题标题】:Retrieve the "Placeholder" value with Javascript in IE without JQuery在没有 JQuery 的情况下在 IE 中使用 Javascript 检索“占位符”值
【发布时间】:2013-04-24 18:34:53
【问题描述】:

我有一些 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;

} 我用的是0%的Jquery,感觉解决小问题太笨重了,另外想学纯Javascript。 Modernizr 也是不行的,尽管我可能会在某个时候开始使用它。

更新

这是工作代码。在 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();

}

【问题讨论】:

  • 随着项目的增长,您会意识到 jQuery 为您节省的时间(即如果您正在使用它)与其他情况相比。
  • 如果你觉得 jQuery 太笨重,你可以看看Zepto.js.. 它更轻。
  • 不要写像if ("placeholder" in test) { var testholder = true; } else { var testholder = false; }这样的代码你会发现var testholder = ("placeholder" in test)做同样的事情。

标签: javascript internet-explorer


【解决方案1】:

如果您不确定是否可以使用某些功能/属性,请尝试caniuse.com - 您会注意到占位符在 IE9 中不可用。

尝试使用getAttribute("placeholder")

getAttribute() 返回指定属性的值 指定的元素。如果命名属性不存在,则值 返回将为 null 或 "" (空字符串);见注释 详情。

EXAMPLE

HTML

<input id="demo" placeholder="Rawr" />

JavaScript

var placeholder = document.getElementById("demo").getAttribute("placeholder");
console.log(placeholder);

【讨论】:

  • @Chase 但在 IE8 中用于密码类型输入,占位符仅显示为点......在这种情况下该怎么做。
  • @RIADev - 这是一个棘手的案例,因此您最终将不得不为它们做一些定制的事情。您可以在 SO 上找到类似的问题,例如:stackoverflow.com/questions/6052544/…。然而,IE8 终于开始被放宽了,所以可能值得问问在你的情况下这是否是一个值得解决的问题。它影响了多少用户等等?值得做出改变吗?等等等等。
  • @Chase 但是如果客户说他们是超级用户......无论如何......我找到了解决方案,谢谢
猜你喜欢
  • 1970-01-01
  • 2019-01-14
  • 1970-01-01
  • 2019-06-13
  • 2015-06-05
  • 1970-01-01
  • 1970-01-01
  • 2014-02-18
  • 1970-01-01
相关资源
最近更新 更多