占位符-用于文本区域输入

Placeholders - For textarea input

本文关键字:区域 输入 文本 用于 占位符      更新时间:2023-09-26

我一直在使用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();
}

提前谢谢。

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

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

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

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

希望它能帮助

只需查询文本区域元素

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();
}