简体   繁体   English

JavaScript - 使用背景图像加载问题输入占位符文本

[英]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.我有一个 input type="text" 字段,我试图用一些默认文本的背景图像替换未被广泛支持的 HTML5 占位符属性。

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).在 JavaScript 中,当表单获得焦点时移除背景图像(这样用户在字段中输入的文本不会与背景图像中的文本重叠)并在输入失去焦点时替换背景图像(我正在使用onBlur事件)。

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."我只是将 onload 事件放入我的 body 元素而不是 input 元素并更改了“this”。 to "document.getElementById('food')."到“document.getElementById('food')”。 because apparently the onload event only works with the document itself (body element) and images.因为显然 onload 事件仅适用于文档本身(正文元素)和图像。

So, this is how my body element looks:所以,这就是我的 body 元素的样子:

<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"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM