问题描述
我正在用JS构建一个UI库,它可以在不依赖任何CSS样式表的情况下创建通过代码进行样式化的UI组件.到目前为止,除了设置不同的控制状态(例如input:focus one)的样式外,这非常容易.
I'm building a UI library in JS that can, without relying on any CSS stylesheets, create UI components, stylised from code. So far, it's been quite easy, with exception of styling different control states (such as input:focus one).
我用来创建输入字段的代码:
Code that I use to create input field:
function newInput()
{
var ctr = docmuent.createElement("input");
ctr.setAttribute("type","text");
ctr.setAttribute("value", some-default-value);
ctr.style.fontFamily = "sans-serif,helvetica,verdana";
/* some font setup here, like color, bold etc... */
ctr.style.width = "256px";
ctr.style.height = "32px";
return ctr;
}
为默认状态设置样式很容易.但是我不确定如何为焦点,禁用或不可编辑的状态设置样式.
Styling it for default state is easy. However I am unsure how to set style for states such as focused, disabled or not-editable.
如果我要在项目中包含CSS样式表,可以很容易地进行整理.但是我没有包含任何CSS文件,它必须是纯JS.
If I'd be having CSS stylesheets included in the project that would be easily sorted out. However I can't have any CSS files included, it must be pure JS.
有人知道直接从JS代码设置输入字段状态(例如input:focus)的样式吗?
Does anyone know how to set style for an input field state (eg. input:focus) straight from JS code?
没有JQuery :-)只需整理JS.
No JQuery please :-) Just straight-up JS.
提前谢谢!
推荐答案
您需要向元素添加事件侦听器,以更改其样式.这是一个非常基本的示例.
You would need to add an event listener to the element in order to change the style of it. Here is a very basic example.
var input = document.getElementById("something");
input.addEventListener("focus", function () {
this.style.backgroundColor = "red";
});
<input type="text" id="something" />
这篇关于如何设置输入:使用JavaScript以编程方式设置焦点样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!