开发者

JavaScript - Input placeholder text using background image onload issue

I have an input type="text" field and am trying to substitute the HTML5 placeholder property that is not widely supported with a background image of some default text.

And in JavaScript, removing the background image when the form receives focus (so that the text the user types in the field does not overlap with the text in the background image) and replacing the background image when the input loses focus (I am using the onBlur event).

This works fine except that when a user types text into the input field, heads to another page without submitting this text and hits the back to previous page button in their browser, the page reloads开发者_高级运维 but with their previous text, that they did not submit, still in the input field on top of the background image.

I tried to fix this by checking if the form has value when the page loads, and if it does then remove the background image but this part isn't working for me.

<input type="text" id="food" onLoad="if(this.value!=''){this.style.backgroundImage='none';}" onFocus="this.style.backgroundImage='none';" onBlur="if(!this.value){this.style.backgroundImage='url(pics/m_form_post.png)';}" name="food"/>

I am open for possible solutions.


I solved it! I just put the onload event into my body element instead of the input element and changed the "this." to "document.getElementById('food')." because apparently the onload event only works with the document itself (body element) and images.

So, this is how my body element looks:

<body onLoad="if(document.getElementById('food').value!=''){document.getElementById('food').style.backgroundImage='none';}">

And this is how my input element looks:

<input type="text" id="food" onFocus="this.style.backgroundImage='none';" onBlur="if(!this.value){this.style.backgroundImage='url(pics/m_form_post.png)';}" name="food"/>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜