如何使用 JavaScript 以编程方式设置输入:焦点样式

问题描述 投票:0回答:6

我正在用 JS 构建一个 UI 库,它可以在不依赖任何 CSS 样式表的情况下创建 UI 组件,并通过代码进行风格化。到目前为止,除了设置不同的控件状态样式(例如输入:焦点之一)之外,一切都非常简单。

我用来创建输入字段的代码:

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;
}

将其设置为默认状态很容易。但是我不确定如何设置诸如聚焦、禁用或不可编辑等状态的样式。

如果我将 CSS 样式表包含在项目中,那么就很容易解决。但是我不能包含任何 CSS 文件,它必须是纯 JS。

有谁知道如何直接从 JS 代码设置输入字段状态的样式(例如 input:focus)?

不要使用 JQuery :-) 只是直接的 JS。

提前致谢!

javascript css stylesheet onfocus
6个回答
7
投票

您需要向元素添加事件侦听器才能更改其样式。这是一个非常基本的例子。

var input = document.getElementById("something");
input.addEventListener("focus", function () {
  this.style.backgroundColor = "red";  
});
<input type="text" id="something" />


5
投票

其他选择是为页面构建样式表。

类似这样的:

 var styles='input:focus {background-color:red}';

 var styleTag=document.createElement('style');
 if (styleTag.styleSheet)
     styleTag.styleSheet.cssText=styles;
 else 
     styleTag.appendChild(document.createTextNode(styles));

 document.getElementsByTagName('head')[0].appendChild(styleTag);

这样您就可以将 css 样式与脚本完全分离,从而更好地进行维护。


5
投票

如果可能,使用 CSS 变量

现在是 2022 年,对于这个问题有更简单的解决方案,而不是在可能永远不会被清理的地方添加事件侦听器。

如果您可以控制 CSS,请执行以下操作:

.my-class {
  --focusHeight: 32px;
  --focusWidth: 256px;
}

.my-class:focus {
  height: var(--focusHeight);
  width: var(--focusWidth);
}

然后在 JavaScript 中,就像使用

setProperty
来更新变量一样简单:

const el = document.getElementById('elementId');
el.style.setProperty('--focusHeight', newFocusHeight);
el.style.setProperty('--focusWidth', newFocusWidth);

1
投票

首先,创建您的输入:

<input type="text" id="myElementID" />

然后添加以下 javascript:

const element = document.getElementById("myElementID");

// Add a box shadow on focus
element.addEventListener("focus", (e) => {
  e.target.style.boxShadow = "0 0 0 3px #006bff40";
});

// Remove the box shadow when the user doesn't focus anymore
element.addEventListener("blur", (e) => {
  e.target.style.boxShadow = "";
});

0
投票

一个快速的 oneliner,它动态地将

style
标签附加到 身体。

document.body.innerHTML += '<style>#foo:focus {background-color:gold}</style>'
<input id="foo"/>


-1
投票

let input = document.querySelector(".input-text");
    let label = document.querySelector('.fields-label');
    input.addEventListener('focus', function(e){
        label.classList.add('is-active');
    })
    input.addEventListener('blur', function(e){
        if(input.value === "") {
            label.classList.remove('is-active');
        }
    })
     label.is-active{
            color:red;
        }
 
    <div class="input-fields">
        <label class="fields-label">Last Name</label>
        <input type="text" class="input-text">
    </div>

    

© www.soinside.com 2019 - 2024. All rights reserved.