[英]problem with changing colour of a textbox
*I want the background colour of a text box to change to lightgreen when the textbox gets focus and its background colour to revert to white when it loses focus. *我希望文本框的背景颜色在文本框获得焦点时变为浅绿色,而在失去焦点时其背景颜色恢复为白色。 My code works perfectly on localhost and when the browser is Safari.
当浏览器为 Safari 时,我的代码在 localhost 上运行良好。
However, with all the other browsers (Chrome, Edge, Firefox, Opera ) nothing happens.但是,对于所有其他浏览器(Chrome、Edge、Firefox、Opera),什么都没有发生。 I'm doing something stupid, but what?!
我在做一些愚蠢的事情,但是什么?!
<script>
function test(id)
{
var ctrl_name = id;
document.getElementById('Name').value = ctrl_name;
}
</script>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery
/1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
$('.clickOnMe').blur(function(){
$(this).css('background', 'white' );
});
$('.clickOnMe').mousedown(function(){
$(this).css( 'background', 'lightgreen');
});
});
</script>
and in the textboxes -在文本框中 -
onclick="test(this.id)" class="clickOnMe"
No error messages/ Simply won't work except on localhost and Safari.*没有错误消息/除了在 localhost 和 Safari 上之外根本无法工作。*
This can be done with css
without javascript.这可以通过没有 javascript 的
css
8CBA22E28EB17B5F5C6AE2A266AZ 来完成。 Example:例子:
.custom-textarea:focus { background-color: lightgreen; }
<textarea class="custom-textarea">Click on me</textarea>
If you would like to use js
and jQuery
anyway: You can use .focus()
event instead of .mousedown()
.如果您仍然想使用
js
和jQuery
:您可以使用.focus()
事件而不是.mousedown()
。
- This method is a shortcut for
.on( "focus", handler )
in the first and second variations, and.trigger( "focus" )
in the third.此方法是第一个和第二个变体中
.on( "focus", handler )
和第三个变体中.trigger( "focus" )
的快捷方式。- The
focus
event is sent to an element when it gains focus.当元素获得焦点时,
focus
事件被发送到元素。- Source: api.jquery.com
来源: api.jquery.com
Example:例子:
$('textarea').focus(function() { $(this).css("background-color","lightgreen"); }); $('textarea').blur(function() { $(this).css("background-color","white"); });
<script src="https://code.jquery.com/jquery-3.4.1.js"></script> <textarea class="custom-textarea">Click on me</textarea>
Or in ES6或者在 ES6 中
$('textarea').focus((e) => $(e.currentTarget).css("background-color","lightgreen")); $('textarea').blur((e) => $(e.currentTarget).css("background-color","white"));
<script src="https://code.jquery.com/jquery-3.4.1.js"></script> <textarea class="custom-textarea">Click on me</textarea>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.