【问题标题】:Placeholders - For textarea input占位符 - 用于文本区域输入
【发布时间】:2012-02-06 19:27:19
【问题描述】:

我一直在使用 JavaScript 占位符脚本来支持 IE 占位符。

适用于输入类型 = 文本。但是如何在脚本中添加支持 textarea 的内容?

我的代码是:

function activatePlaceholders() {
var detect = navigator.userAgent.toLowerCase();
if (detect.indexOf("safari") > 0) return false;
var inputs = document.getElementsByTagName("input");
for (var i=0;i<inputs.length;i++) {
  if (inputs[i].getAttribute("type") == "text") {
   if (inputs[i].getAttribute("placeholder") && inputs[i].getAttribute("placeholder").length > 0) {
    inputs[i].value = inputs[i].getAttribute("placeholder");
    inputs[i].onclick = function() {
     if (this.value == this.getAttribute("placeholder")) {
      this.value = "";
     }
     return false;
    }
    inputs[i].onblur = function() {
     if (this.value.length < 1) {
      this.value = this.getAttribute("placeholder");
     }
    }
   }
  }
}
}
window.onload=function() {
activatePlaceholders();
}

提前致谢。

【问题讨论】:

    标签: javascript placeholder


    【解决方案1】:

    textarea 不是输入类型。它本身就是一个标签。示例

    <textarea rows=10 placeholder="Enter text here"></textarea>
    

    在这种情况下,您的代码可以是

    var inputs = document.getElementsByTagName("textarea");
    inputs[0].setAttribute('placeholder','New placeholder');
    

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      简单查询文本区域元素

      function activatePlaceholders() {
      var detect = navigator.userAgent.toLowerCase();
      if (detect.indexOf("safari") > 0) return false;
      var inputs = document.getElementsByTagName("textarea");
      for (var i=0;i<inputs.length;i++) {
      
         if (inputs[i].getAttribute("placeholder") && inputs[i].getAttribute("placeholder").length > 0) {
          inputs[i].value = inputs[i].getAttribute("placeholder");
          inputs[i].onclick = function() {
           if (this.value == this.getAttribute("placeholder")) {
            this.value = "";
           }
           return false;
          }
          inputs[i].onblur = function() {
           if (this.value.length < 1) {
            this.value = this.getAttribute("placeholder");
           }
          }
        }
      }
      }
      window.onload=function() {
      activatePlaceholders();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-09
        • 2013-11-18
        • 1970-01-01
        • 2015-10-25
        • 2021-10-31
        • 2015-06-05
        • 2013-09-15
        • 2013-07-07
        相关资源
        最近更新 更多