不显眼的“默认"没有jQuery的输入文本 [英] unobtrusive "default" text in input WITHOUT jQuery

查看:27
本文介绍了不显眼的“默认"没有jQuery的输入文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

i'm trying to write unobtrusive default/placeholder text in input (actually, relatively placed label over input, which hides on onFocus, and stays hidden if input isn't empty on onBlur), but I don't want to use jQuery, because this is the only javascript used on page - therefore using jQuery seems a bit over the top.

Please, how can I do this without jQuery?

Thank you.

EDIT: I know the idea (getElementByID), but I'm more looking into how to add it to document - preferably something you have used before. Thank you.

EDIT: Thank you all, I finally went with jQuery, seeing answers :] (my example is here: http://jsbin.com/ehega/3 - it's concept, I'll probably add more eye candy. As an answer I Robert Koritnik - because of valid points... and styling ;])

解决方案

I suggest you use jQuery

jQuery is nothing more than a cross-browser library that makes it easier for developers to achieve something and not worry about browser particularities. And when you load it once (it's rather small) it's cached so I wouldn't worry because it will save you lots of development/testing time later.

No? Then do it manually but make it more reusable

But if you do decide to do something manually you can always use regular Javascript and manipulate DOM as you wish. You best friends in this case would of course be (as Andrew pointed out):

  • getElementById() and
  • getElementsByTagName()

functions, but since you'll be manipulating DOM and styles, make sure you test your code against all common browsers. If you use custom attributes on INPUT elements it's good to use the second function, so you'll attach additional functionality to all inputs at once and only to those that define that particular custom attribute like:

<input type=text id="inputX" name="inputX" placeholder="Enter something">

Your script would then get all inputs and you'd check for the custom attribute existance and attach events to those elements that do define that attribute. This way you won't depend on IDs and make your code universal so you can reuse it app wide. Or even on other projects.

Just a sidenote: Andrew's example works somehow differently than what you said would like to do (using labels), but I suggest you use the same approach, because you'll be running scripts anyway. For the sake of unobtrusiveness make sure that you set default content using Javascript so default values and styles on textboxes won't be set for those users that are not running Javascript.

这篇关于不显眼的“默认"没有jQuery的输入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆